[Swift] Subscripts

East Silver·2021년 12월 30일
0

애플 공식 문서를 바탕으로 정리합니다!

Subscripts

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.

Subscript Syntax

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"
  • 리턴 타입 생략 불가
  • get 블록만 있는 읽기전용 가능. set 블록만 있는건 불가능
  • argument label 은 따로 선언 해줘야함. 파라미터 레이블로 대체할 수 없음. 드물게 가독성을 높혀주고 싶을때만 사용.

Subscript Usage

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

Subscript Options

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.

Type Subscripts

서브 스크립트도 타입 자체로 접근할 수 있는 타입 서브 스크립트가 존재한다. 지금까지의 방식과 동일하게 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)```
profile
IOS programmer가 되고 싶다

0개의 댓글