iOS/Swift

[Swift] 문자열 리터럴(String Literals)

Dev.Andy 2023. 4. 8. 23:50

프로그래밍 언어의 기본 자료형 중 하나인 문자열에 대해 알아 보자. Swift는 문자열과 문자를 별도로 구분하는 언어이다.

(아래의 여러 줄 문자열은 루이스 캐럴의 소설 『이상한 나라의 앨리스』(1865) 발췌하여 가져 왔습니다.)

 

📌 문자열 리터럴(String Literals)

문자열의 리터럴은 쌍따옴표 하나(")를 양끝에 감싸서 데이터를 표현한다.

// 타입 추론 형식으로 문자열을 작성할 때
let aString = "This is a string."

// 타입 명시로 문자열을 작성할 때
let anotherString: String = "I just wrote my second string."

 

📌 여러 줄 문자열 리터럴(Multiline String Literals)

(1) 쌍따옴표 3개(""")를 양끝에 감싸서 여러 줄의 문자열을 표현할 수 있다. 여러 줄 문자열에서 줄바꿈(\n)을 포함하면 줄바꿈 또한 문자열의 값으로 나타난다.

let aQuote = """
Alice was beginning to get very tired of sitting by her sister
on the bank, and of having nothing to do: once or twice she had
peeped into the book her sister was reading, but it had no pic-
tures or conversations in it, "and what is the use of a book,"
thought Alice, "without pictures or conversations?"
"""

 

(2) 소스코드를 쉽게 읽고자 줄바꿈을 쓰되, 줄바꿈이 문자열의 일부가 되지 않을 경우 라인 끝마다 역슬래시(\)를 쓰면 된다.

let anotherQuote = """
In another moment down went Alice after it, never once \
considering how in the world she was to get out again.

The rabbit-hole went straight on like a tunnel for some way, and \
then dipped suddenly down, so suddenly that Alice had not a ...
"""

 

(3) 여러 줄 문자열의 들여쓰기는 맨끝의 닫는 따옴표(""")를 기준으로 공백을 무시할 수 있다. 만약 닫는 따옴표보다 추가로 공백이 더 들어가면 그 공백은 추가 된다.

let theOtherQuote = """
    There was nothing so very remarkable in that; nor did Alice
    think it so very much out of the way to hear the Rabbit say
      to itself, "Oh dear! Oh dear! I shall be too late!"
    """

4번 줄의 to itself 옆에 공백(" ") 2개를 두었는데 이를 출력하면 공백 2개가 반영되어 출력된다.

 

(4) 닫는 따옴표보다 더 앞에 있으면 에러를 반환한다.

let rabbitHoleQuote = """
    Alice was not a bit hurt, and she jumped up on to her feet
    in a moment : she looked up, but it was all dark overhead;
    before her was another long passage, and the White Rabbit was
still in sight, hurrying down it.
    """

5번 줄이 6번 줄의 닫는 따옴표보다 앞에 있기 때문에 에러를 반환한다.

error: insufficient indentation of line in multi-line string literal