article thumbnail image
Published 2022. 10. 5. 15:53

Subscript란,

Collection, List, Sequence 등 집합의 특정 member elements에 간단하게 접근할 수 있는 Type properties

subscript 사용으로 추가적인 methods 없이 특정 값에 할당하거나 가져올 수 있다.

 

Array의 경우 []안의 index를 통해 member elements 접근

→ 즉 index는 subsrcript

var arr: [String] = ["가", "나", "다", "라"]

arr[1] //get
arr[1] = "가나다" //set

→ 실제 Array안에 선언되어 있는 subscript

subscript(index: Int) -> Element { get set }

 

Dictionary의 경우도 마찬가지로 key를 parameter로 가지게 되어, key값으로 접근이 가능하다.

subscript(key: Key) -> Value? { get set }

subscript in String

var str: String = "string"
str[0] //Error

Swift의 경우에는 String타입을 배열과 같이 subscript를 통해 접근 하면 에러가 뜬다. 에러가 뜨는 이유를 살펴보자.

우선, Apple Documentation의 정의된 String을 살펴보면 characters의 collection인 Unicode value의 struct타입이라고 나와있다.

여기서, 유심하게 봐야 하는것은 Unicode를 사용한다는 것이다.

기존 ASCII는 7bits고정값으로 문자를 할당 하였지만,

Unicode는 더 많은 문자를 표현하기 위해 최소 1byte에서 크기가 가변적으로 변한다.

 

기존 C, C++ 등의 언어에서는 String은 크기가 고정된 ASCII 드를 사용하였지만, 

Swift에서는 크키가 가변적인 Unicode를 사용하기에 한 문자가 1byte라는 것을 보증할 수 없다.

이러한 이유로 Swift에서는 index를 통한 접근이 불가능하다!

그렇다면, Swift에서는 String 특정 index에 접근할까?

 

정답은 index method를 사용하는 것이다. 

func index(_ i: String.Index, offsetBy n: String.IndexDistance) -> String.Index
var str: String = "string"
str.index(0) //s

 

 

Swift은 Struct이기 때문에 subscript 정의하여 사용할 수 있다. 

extension String {
    subscript(index: Int) -> String? {
        guard index >= 0 && index < self.count else {
            return nil
        }
        let target = self.index(self.startIndex, offsetBy: index)
        return String(self[target])
    }
}
var str: String = "string"
str[0] //s

 

 

 

'iOS > Swift' 카테고리의 다른 글

[Swift] KVO, Delegate and Notification  (2) 2022.10.08
[Swift] Notification  (0) 2022.10.08
[Swift] Delegate  (0) 2022.10.07
[Swift] KVO (Key-Value-Observing)  (0) 2022.10.06
[Swift] KVC (Key-Value-Coding)  (1) 2022.10.05
복사했습니다!