애플 공식 문서를 바탕으로 정리합니다!
Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"
Subscripts are typically used as a shortcut for accessing the member elements in a collection, list, or sequence.
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
Subscripts can take any number of input parameters, and these input parameters can be of any type. Subscripts can also return a value of any type.
Like functions, subscripts can take a varying number of parameters and provide default values for their parameters, as discussed in Variadic Parameters and Default Parameter Values. However, unlike functions, subscripts can’t use in-out parameters.
서브 스크립트도 타입 자체로 접근할 수 있는 타입 서브 스크립트가 존재한다. 지금까지의 방식과 동일하게 static 키워드를 사용하면 정의할 수 있고 클래스에서는 class 키워드로 타입 서브 스크립트를 정의할 수 있다.
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)```