Swift - String(2)

캣코타·2022년 1월 17일
0

Swift-String

목록 보기
2/2

Modifying and Comparing

String타입으로 선언한 변수를 다른 값으로 할당하면 어떻게 될까? String은 Struct 으로 구현되어있기 때문에 Struct의 문법(sementics)를 따른다. 즉 값복사가 일어난다!

var greeting = "Welcome!"
var otherGreeting = greeting
otherGreeting += " Have a nice time!"

print(otehrGreeting)
//"Welcome! Have a nice time!"

print(greeting)
//"Welcome!"

그렇담 비교는? String의 equality(동등성)을 비교할 땐 `Unicode canonical representation` 을 사용해 동작한다(is performed). 결과적으론 string을 Unicode방식으로 표현하던 literal로 표현하던 동일하다면 `비교`의 결과는 `true` 라는 것!
let cafe1 = "Cafe\u{301}"
let cafe2 = "Café"
print(cafe1 == cafe2)
// Prints "true"
  • 자세한 설명 : The Unicode scalar value "\u{301}" modifies the preceding character to include an accent, so "e\u{301}" has the same canonical representation as the single Unicode scalar value "é"

또한 기본적으로 string operation(문자열을 제공하는 것)은 지역적인 차이(locale setting)에 민감하지 않으므로(not sensitive) string comparison 즉 string을 이용해 비교하는 것과 string을 이용한 operation은 언제나 하나의, 안전한 결과값을 보장하기 때문에 Dicationary의 keys 로서 사용할 수 있고 다른 목적으로도 사용가능하다.


Accessing String Element, 문자열 요소에 접근하기

String은 extended grapheme clusters 즉, 인간이 읽을 수 있는(human-readable) 문자(character)의 집합(collection)이라고 말한다.
(extended : 확장된, grapheme : 자소, 또는 낱글자는 어떤 언어의 문자 체계에서 의미상 구별할 수 있는 가장 작은 단위, cluster : 하나의 덩어리)

OverView에서 단지 문자의 집합이라고 말했던것 보다 확장된 개념을 말하고 있다.


각각의 문자들은 Unicode scalar 값으로 표현되며 이는 유니코드의 boundary 알고리즘에 의해 *`extended grapheme clusters`* 로 합쳐지고(combined) 이는 Swift에서 `Character` type으로 표현된다.

유니코드 스칼라 값(Unicode scalar Value) : 유니코드 스칼라 값은 유니코드 "문자"에 배당된 숫자로, 통상 "U+" 뒤에 4~6자리 16진수로 표기한다.
출처

이러한 특성으로 String은 양수 인덱스로 접근이 불가능하며 firstIndex, endIndex 등의 메소드 혹은 속성을 이용해 String의 일부분(subString)을 가져온다.

let name = "Marie Curie"
let firstSpace = name.firstIndex(of: " ") ?? name.endIndex
let firstName = name[..<firstSpace]
// 이 때 firstName의 타입은 subString
// firstName == "Marie"

SubString 타입은 말 그대로 String의 일부분을 의미한다. 또한 SubString은 String이 저장된 original storage의 일부를 sharing한다. 즉 하나의 standalone 인스턴스로 존재하지 않는다.

SubString 을 하나의 String 인스턴스로 만드는 방법 init(_ substring: Substring) 이용하기

let firstName = name[..<firstSpace]
let newFirstName = String.init(firstName)
profile
to be iOS Developer

0개의 댓글