본문 바로가기
Swift

알쓸스잡 - 4

by songmoro 2024. 12. 30.
728x90

여러 줄 문자열 리터럴

여러 줄 문자열 리터럴은 줄 바꿈을 포함
만약, 문자열의 줄바꿈을 원치 않는다면 역슬래시 사용

 

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)

// 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."

 

확장된 문자열 구분기호

문자열에 특수 기호를 포함하기 위해 확장된 문자열 구분기호를 사용

let a = #" a "#
let b = #"""
b
"""#

print(a, b)
//  a  b

 

특수 기호 효과를 적용하고 싶다면

  • 역슬래시 + #
let a = #" a "#
let b = #"""
\#nb
"""#

print(a, b)
//  a  
// b

 

빈 문자열 초기화

아래 두 방법은 결과적으로 같음

let emptyString = ""
let anotherEmptyString = String()

print(emptyString.isEmpty, anotherEmptyString.isEmpty)
print(emptyString == anotherEmptyString)

// true, true
// true

 

문자열은 값 타입

Swift의 String은 값 타입

  • 새로운 String 값을 생성한다면, String 값은 함수 또는 메서드에 전달될 때나, 상수 또는 변수에 대입될 때 복사됨
  • 각 경우에 존재하는 String 값의 새로운 복사본이 생성되고, 원본이 아닌 새로운 복사본은 전달되거나 할당됨

 

확장된 문자소 클러스터

Swift의 Character 타입의 모든 인스턴스는 하나의 확장된 문자소 클러스터로 표기

 

확장된 문자소 클러스터

  • 하나 이상의 유니코드 스칼라로 구성된 결합되었을 때 사람이 읽을 수 있는 하나의 문자
  • 많은 복잡한 스크립트 문자를 하나의 Character 값으로 표기하는 방법
let eAcute: Character = "\u{E9}"                         // é
let combinedEAcute: Character = "\u{65}\u{301}"          // e followed by ́
// eAcute is é, combinedEAcute is é

let precomposed: Character = "\u{D55C}"                  // 한
let decomposed: Character = "\u{1112}\u{1161}\u{11AB}"   // ᄒ, ᅡ, ᆫ
// precomposed is 한, decomposed is 한

let regionalIndicatorForUS: Character = "\u{1F1FA}\u{1F1F8}"
// regionalIndicatorForUS is 🇺🇸

 

문자열 인덱스

String 값의 인덱스는 String.Index를 사용

  • 확장된 문자소 클러스터는 여러개의 유니코드 스칼라로 구성
    • 이 때문에 Swift의 문자는 각각 문자열에서 동일한 양의 메모리를 차지하지 않음
  • 문자마다 저장할 메모리 양이 다를 수 있으므로 특정 위치에 있는 Character를 확인하려면 해당 String의 시작 또는 끝에서 각 유니코드 스칼라를 반복
    • 이러한 이유로 Swift 문자열은 정수값으로 인덱스를 생성할 수 없다.

 

부분 문자열

문자열에서 부분 문자열을 얻을 때, 그 결과는 또다른 문자열이 아닌 Substring의 인스턴스

 

부분 문자열의 장단점

  • 단기적으로 메모리 복사에 대한 비용을 지불하지 않아도 됨
  • 장기적으로 원래 문자열의 저장소를 재사용하기 때문에 저장 시 전체 원본 문자열을 메모리에 보관해야 함

let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index]
// beginning is "Hello"


// Convert the result to a String for long-term storage.
let newString = String(beginning)

 

참고

https://bbiguduk.github.io/swift-book-korean/documentation/the-swift-programming-language-korean/stringsandcharacters
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators

728x90

'Swift' 카테고리의 다른 글

알쓸스잡 - 6  (0) 2025.01.21
알쓸스잡 - 5  (0) 2025.01.17
알쓸스잡 - 3  (1) 2024.12.30
알쓸스잡 - 2  (0) 2024.12.26
알쓸스잡 - 1  (2) 2024.12.25