Featured image of post String Literals

String Literals

Literals ❓

Literal은 각 자료형에 대한 값을 표현하는 방법이다. 상수나 변수로 정의되는 데이터 그 자체 - 라고 표현하면 더 이해가 쉬울 듯 하다.

예를 들면, 문자열 리터럴은 “Hello, World”, 정수형 리터럴은 12345 등으로 표현할 수 있다.

공식문서를 보면서 String Literals에 대해 공부해 보았다.

String Literals

A string literal is a sequence of characters surrounded by double quotation marks (").

1
2
let someString = "Some string literal value"
print(someString) // Some string literal value

한줄로 된 문자열을 정의할 때는 이렇게 하면 된다. 줄바꿈을 하고 싶은 경우에는 \n을 사용해준다.

1
2
3
4
let someString = "Some string \n literal value"
print(someString)
// Some string
// literal value

Multiline String Literals

여러 줄의 문자열 리터럴을 정의할 때에는 앞,뒤로 """를 붙여주면 된다.

1
2
3
4
5
6
7
let quotation = """
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."
"""

print(quotation)해 보면 이렇게 출력된다.

img

""" 블록 안에서 줄바꿈을 하면 문자열에도 줄 바꿈이 적용되는데. 만약 코드의 가독성을 위해 줄바꿈을 하지만 문자열에는 적용되지 않게 하고 싶다면 \를 붙여주면 된다.

1
2
3
4
5
6
7
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."
"""

print(softWrappedQuotation)해 보면 이렇게 출력된다.

img

들여쓰기 기준은 뒤쪽 """앞 부분이 기준이 된다. 하단의 코드를 보면 뒤의 """앞에 4칸의 공백이 있으므로 다른 열의 4칸의 공백도 함께 무시되고, 그 이후의 들여쓰기만 적용된다.

img

1
2
3
4
5
let lineWithIndentation = """
    This line doesn't begin with whitespace
        This line begins with four space
    This line doesn't begin with whitespace
    """

print(lineWithIndentation)해 보면 이렇게 출력된다.

img

이해되지 않은 부분

공식문서에서 Multiline String Literals"""를 사용하기 때문에 하나 이상의 "를 이스케이프 해주면 "를 문자열에서 사용할 수 있다고 나와있는데

Because multiline string literals use three double quotation marks instead of just one, you can include a double quotation mark (") inside of a multiline string literal without escaping it. To include the text """ in a multiline string, escape at least one of the quotation marks. For example:

1
2
3
4
let threeDoubleQuotationMarks = """
Escaping the first quotation mark \"""
Escaping all three quotation marks \"\"\"
"""

이 코드를 XCode로 실행하면 """ 뒷부분도 문자열로 인식된다.

img

심플한 코드를 만들어서 확인해 보았다. img

Xcode상에서 이후의 코드가 주황색으로 보여지긴 하지만 빌드도, 실행도 잘 되어진다.

img

이런 거 Apple에 보고하려면 어떻게 해야 하는지 아시는 분?

Reference

Swift Docs - Strings and Characters