Apple-CS-interview / iOS-CS-interview

7 stars 0 forks source link

String은 왜 subscript로 접근이 안되는지 설명하시오. #9

Open ronick-grammer opened 1 year ago

ronick-grammer commented 1 year ago

String의 요소는 Int형을 파라미터로 사용해 subscript로 접근이 안되는 이유


#### Swift의 문자는 유니코드를 준수하여 표기된다
- 유니코드 문자는 크기가 가변적이기 때문에 하나의 문자가 하나의 바이트보다 클 수 있다.
- 하나의 문자가 하나이상의 바이트를 차지할 수 있기때문에, 일반적인 문자열 배열처럼(다른 언어의 문자열 배열처럼) 1 바이트 단위인 인덱스로 특정 문자에 접근할 수가 없다.
- 유니코드 표현방식으로는 `utf8(8bit)`, `utf16(16bit)`, `utf32(32bit)`가 존재하며 Swift에서는 `Unicode Scalar(21bit)`가 존재한다.

*유니코드: 존재하는 모든 문자를 모든 플랫폼에 일관되게 표현하고 다룰 수 있도록 설계된 산업 표준 문자코드이다

#### Swift 의 `String`, `Character` 타입은 `Unicode Scalar` 값으로 이루어져 있다.
- Character 타입은 하나이상의 Unicode Scalar 값으로 구성되어 있다.
```swift
let character1: Character = "\u{D55C}"                  // '한'
let character2: Character = "\u{1112}\u{1161}\u{11AB}"   // 'ᄒ, ᅡ, ᆫ' == '한'

Stringsubscript를 통해 요소에 접근할때 순차적으로 순회한다.

String의 요소를 Int형 파라미터를 사용해 subscript로 접근할 수 있는 방법

extension String {
    subscript(idx: Int) -> String? {
        guard (0..<count).contains(idx) else {
            return nil
        }
        let target = index(startIndex, offsetBy: idx)
        return String(self[target])
    }
}

let str = "ronick"
str[2] // "n"
str[7] // nil

📝 참고 사이트

Do-hyun-Kim commented 1 year ago

String은 왜 subscript로 접근이 안되는지 설명하시오.

Unicode scalar 란?

  • 크기가 가변적인 String 문자열을 하나하나 개별적으로 접근하기 위한 방법
  • Unicode 기반 21-bit 코드
  • 하나 이상의 Unicode scalar가 모여 Character를 이룬다 .

Extended Grapheme Cluster 란?

  • Swift의 모든 Character type은 하나의 확장된 Grapheme Cluster로 나타낸다.
  • 한개 이상의 Unicode sclar 시퀸스로 사람이 읽을 수 있는 문자를 생성한다.
let usFlag: Character = "\u{1F1FA}\u{1F1F8}"
print(usFlag)

🤔 Swift에서 String을 subscript하는 방법은??

extension String {
    subscript(index: Int) -> Character {

        return self[self.index(self.startIndex, offsetBy: index)]

    }

}

var name: String = "jenny"
for i in 0 ..< name.count {
    print(name[i])
}

📝 참고 사이트

vichye-1 commented 1 year ago

Swift 의 String

Swift에서 하나(🍎)의 String이 다양한 조합으로 이루어져 있음을 보여주는 예

let apple = "🍎"

print("Characters count : \(apple.count)")
for i in apple {
    print(type(of: i), i)
    if i == apple.last {
        print("********************")
    }
}

print("Unicode Scalar's count : \(apple.unicodeScalars.count)")
for i in apple.unicodeScalars {
    print(type(of: i), i)
    if i == apple.unicodeScalars.last {
        print("********************")
    }
}

print("utf8 Scalar's count : \(apple.utf8.count)")
for i in apple.utf8 {
    print(type(of: i), i)
    if i == apple.utf8.last {
        print("********************")
    }
}

print("utf16 Scalar's count : \(apple.utf16.count)")
for i in apple.utf16 {
    print(type(of: i), i)
    if i == apple.utf16.last {
        print("********************")
    }
}
Characters count : 1
Character 🍎
********************
Unicode Scalar's count : 1
Scalar 🍎
********************
utf8 Scalar's count : 4
UInt8 240
UInt8 159
UInt8 141
UInt8 142
********************
utf16 Scalar's count : 2
UInt16 55356
UInt16 57166
********************

String에 접근하는 방법

스크린샷 2023-08-22 오후 11 09 01
let sentence = "Accessing String View Elements"
let firstSpace = sentence.firstIndex(of: " ") ?? sentence.endIndex
let firstWord = sentence[..<firstSpace]
print(firstWord)

//Accessing

📝 참고

Hminchae commented 1 year ago

Subscripts란?

subscript(index: Int) -> Int {
    get {
        // 적절한 반환 값
    }
    set(newValue) {
        // 적절한 set 액션
    }
}

String이 subscript로 접근이 안 되는 이유

Swift에서 String은 가변의 크기를 가지기 때문에 Int 기반의 인덱스 참조가 불가능

Unicode scalar란 크기가 가변적인 String 문자열을 하나하나 개별적으로 접근하기 위한 방법으로, 하나 이상의 Unicode Scalar가 모여 Character를 이루고, Character들이 모여 String이 됨

📝 참조