IOS Swift

Swift) Subscript

500beckwon 2023. 2. 21. 19:10

Subscript(서브스크립트)

- 클래스, 구조체, 열거형에서 시퀀스의 멤버 요소에 접근하기 위한 바로가기 첨자라고 합니다

아주 쉽게 예시로 말하면

배열에 인덱상 할때 '배열[0]' 를 하게 해주는 문법입니다 

let num = [1,2,3,4,5]
num[1]
num[4] 
// 이 접근이 subscript

 

Swift에서는 String을 파이썬처럼 "hello"[1] 이런식으로 사용을 할 수 없는데 subscript를 정의하면 사용할 수 있습니다

 

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

이런 식으로 옵셔널로 반환하게 되지만 배열에 인덱싱하는 것처럼 사용할 수 있습니다

 

startIndex는 string의 첫번째 String.Index  타입을 리턴하는 인스턴스 프로퍼티입니다

 

index(_ i: String.Index, offsetBy distance: Int) -> String.Index

이 문법은 i 부터 distance까지 떨어진 String.Index를 리턴하는 함수입니다

 

"Hello"[String.Index]로 접근하는걸 Subscript에 위 로직을 적용하

 

let text = "Hello, World"

print("""
      \(text[1])
      \(text[4])
      \(text[5])
      \(text[22])
      
      """)
/*      
Optional("e")
Optional(",")
Optional(" ")
nil
*/

이렇게 "hello"[1],  "hello"[2] 이렇게 접근 할 수 있습니다