우리가 collection의 요소에 접근하려 할 때 사용하는 subscript
ex. arr[index]로 array의 요소에 접근하기, dic[key]로 dic의 요소에 접근하기
이런 subscript를 직접 만들어
사용자 타입의 인스턴스의 요소에 접근할 수 있도록 할 수 있다!
subscript
키워드로 subscript를 정의한다.subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
get
set
newValue
를 활용한 계산 수행구구단을 나타내는 구조체 TimesTable
을 만들어보자.
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
정의한 subscript 구문에서는
구조체 프로퍼티 multiplier와 index 파라미터의 값의 곱을 return하도록 했다.
let threeTimesTable = TimesTable(multiplier: 3)
print(threeTimesTable[0]) // 0
print(threeTimesTable[1]) // 3
print(threeTimesTable[2]) // 6
print(threeTimesTable[6]) // 18
구조체 인스턴스를 만들어 multiplier로 3을 넣고, threeTimesTable의
0번째 요소에 접근하면 3*0 = 0
1번째 요소에 접근하면 3*1 = 3
2번째 요소에 접근하면 3*2 = 6
6번째 요소에 접근하면 3*6 = 18
이처럼 subscript 구문을 사용해서 우리가 직접 만든 타입 인스턴스의 요소에 접근할 수 있다.
파라미터와 리턴 타입을 다양하게 작성하여 여러 개의 subscript 구문을 정의할 수 있음 .
의도에 맞게 subscript 구문을 정의하고 접근하면 된다.
struct Point {
var x: Int
var y: Int
subscript(coordinate: String) -> Int {
return coordinate == "x" ? x : y
}
subscript(index: Int) -> Int {
return index == 0 ? x : y
}
}
var point = Point(x: 3, y: 5)
print(point["x"]) // 3
print(point[0]) // 3
타입 프로퍼티, 타입 메서드처럼 타입 자체에서 호출되는 subscript를 정의할 수 있다.
static
키워드 작성하기
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
static subscript(n: Int) -> Planet {
return Planet(rawValue: n)!
}
}
let mars = Planet[4]
print(mars) // mars
static
대신 class
키워드 사용하기