본문 바로가기
Swift/Language Guide

Strings and Characters - #1/2

by diosmio 2021. 9. 6.

출처 : https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html

 

Content

- 서문

- String Literals

- Initializing Empty String 

- String mutability (let / var)

- Strings Are Value Types

- Working with Characters (Character에 대하여)

- Concatenating Strings and Characters 

- String Interpolation (문자열 보간법)

 

 

서문

서문의 내용들은 어차피 이후에 전부 자세히 언급되므로 (내기준)특이한 것만 기록해보자


● Swift에서 문자(열)은 Unicode를 따른다

-> 문자 1개가 1Byte가 아닐 수 있겠구나

-> 인코딩 방식은 유니코드의 것 중 사용해야 하구나

 

● 상.변수, 리터럴 등의 표현으로 long string을 만드는걸 "String Interpolation"이라고 한다

-> 문자열 보간법

 

● Foundation의 NSString class는 Swift의 String extend한 것이다.

-> Foundation을 import하면 따로 명시가 없어도 String이 NSString으로 전부 캐스팅되는 효과

 

 

 

String Literals

String Literal을 쓸 수 있다

 

Multiline String Literals

너무 길어서 여러 줄로 표현하고 싶으면 """ 로 묶으면 되는데

첫 줄과 마지막 줄은 """만 있어야 한다

 

● 참고로, line이 바뀌면 엔터가 자동으로 먹으므로 연결하고 싶으면 \를 붙이자

let singleLineString = "These are the same."
let multilineString = """
These are the same.
These are the different.
"""

let softWrappedQuotation = """
The White Rabbit put on his spectacles.  "Where shall I begin, \
please your Majesty?" he asked.

"Begin at the beginning," the King said gravely, "and go on \
till you come to the end; then stop."
"""

 

● 들여쓰기는 마지막 줄의 """ 위치가 기준이 된다

"""가 더 뒤에 있으면 컴파일 에러유발

 

 

Special Characters in String Literals

 

● 이런 것도 당연히 쓸 수 있다

\0 = null

\\ = backslash

\t = tab

\n = new line

\" = 쌍따옴표 (multiline에선 \없이 써도 됨)

\' = 작은따옴표

 

● 그리고, Unicode를 따르기에 다른 언어와 달리 이모티콘 같은 것도 쓸 수 있다 - "\u{n}"

유니코드에 대해선 따로 자세히 설명할 예정이니 지금은 넘어가자

let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}"        // $,  Unicode scalar U+0024
let blackHeart = "\u{2665}"      // ♥,  Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496

 

Extended String Delimiters (구분자)

 

● 위에서 본 \n 이런 것들이 특수한 효과를 내지 않고 문자 그대로 출력하고 싶으면?

-> #으로 감싸면 된다

let abc = #"Line 1\nLine 2"#
//Line 1\nLine 2

 

● 일부는 특수효과를 내고 싶다면?

-> 사이에 #을 넣어주면 된다 - \#n

let abc = #"Line 1\#nLine 2"#
//Line 1
//Line 2

 

 

 

Initializing an Empty String

● 나중에 이어붙이려고 빈 문자열 만드는 방법은 2가지이며,

둘의 결과는 완전히 동일하다

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax
// these two strings are both empty, and are equivalent to each other

 

 

 

String Mutability (가변성)

● String이 가변성을 가지면 var로, 아니면 let으로 선언하면 된다

 

● 주목할 점은, NSString을 쓸 때는 var/let으로 구분하지 않고

class에 차이를 둔다. 변수 String에 대해 NSMutableString 클래스를 사용한다

 

이건 나중에 NSString 할때 알아보자;;

 

 

 

 

Strings Are Value Types

● Swift에서 String은 값타입으로 함수로 전달하거나 다른 상.변수에 assign하면

-> 원본을 copy하여 new 인스턴스가 들어간다

 

● 이런 값타입 구현의 이유는 아마도.. threading과 관련있지 않을까 싶다

String이 어떤 함수 안에 들어온 시점부터 함수 내에서 건드리지 않는 한 바뀌지 않는다

(참조타입이라면 같은 String을 다른 곳에서 바꿀 수 있음)

 

● 사실.. 무조건 copy하는건 아니고 퍼포먼스를 위해

Compiler가 꼭 필요할때만 copy로 동작시킨다고 한다

 

 

 

Working with Characters

● for-in으로 String의 각 character에 접근할 수 있다

for character in "Dog!🐶" {
    print(character)
}
// D
// o
// g
// !
// 🐶

 

● 그리고, Character라는 single 문자 타입도 있긴 하며

배열로 만들면 String으로 캐스팅할 수 있다

let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"

 

 

 

 

Concatenating Strings and Characters

 

문자열 붙이는 표현을 알아보자

 

● 덧셈 연산자 (+ / +=)

let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"

var instruction = "look over"
instruction += string2
// instruction now equals "look over there"

 

● Character를 append하기

let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"

 

주의 : Multiline을 concatenate할 때는 line break가 없는게 어색할 수 있으니 주의하라

single-line과 동작은 같은데 뭔가 어색함

let badStart = """
one
two
"""
let end = """
three
"""
print(badStart + end)
// Prints two lines:
// one
// twothree

let goodStart = """
one
two

"""
print(goodStart + end)
// Prints three lines:
// one
// two
// three

 

 

 

 

String Interpolation (문자열 보간법)

 

상.변수, 리터럴과 각종 타입들을 mix하여 String으로 편하게 만드는 방법을 뜻한다

 

● 사용법은 backslash(\)와 소괄호로 묶어주면 된다.

연산값도 가능하다

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message is "3 times 2.5 is 7.5"

 

● 특수효과를 없애려면 마찬가지로 #을 활용할 수 있다 -> \#( )로 사용

print(#"6 times 7 is \#(6 * 7)."#)
// Prints "6 times 7 is 42."

'Swift > Language Guide' 카테고리의 다른 글

Functions - #1/1  (0) 2021.09.12
Type Casting - #1/1  (0) 2021.09.10
Collection Types - #2/2 : Set, Dictionary  (0) 2021.09.10
Collection Types - #1/2 : Array  (0) 2021.09.09
Strings and Characters - #2/2  (0) 2021.09.06

댓글