Open vichye-1 opened 1 year ago
collection의 요소에 접근할 수 있으며, 클래스, 구조체, 열거형에서 사용할 수 있다.
someArray[index]로 Array의 인덱스에 접근할 수 있으며, someDictionary[Key]로 Dictionary의 Value에 접근할 수 있다.
서브스크립트가 구현된 문법은 계산 프로퍼티의 구문과 비슷하게 getter와 setter로 동작된다.
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
Subscripts
가 구현된 문법은 get
, set
메서드와 동일하다.Subscripts
는 오버로딩이 가능하며, 입력 인자의 숫자 제한이 없으며, 입력 인자의 타입과 반환 타입의 제한도 없다.subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
Subscripts
는 인스턴스를 생성하여 Subscript
를 통해 멤버 요소에 접근 할 수 있지만 static
키워드를 사용하면 인스턴스를 생성 할 필요 없이 타입 자체에서 Subscript
를 통해 멤버 요소에 접근 할 수 있다.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)
Subscripts란
class
,struct
그리고enum
타입에서 배열의 인덱스처럼 데이터의 특정 요소에 접근할 수 있도록 해주는 Swift의 문법이다.Subscript의 기본 형태
subsscript
는computed-property
(연산 프로퍼티) 처럼getter
와setter
를 지정한다.read-only
orread and write
로 동작한다. (아래 예시는read-only
)Array와 Dictionary
Swift의 데이터 타입인
Array
와Dictionary
도 인덱스를 통해 값을 할당/접근 할때, Subscript를 사용한다는 것을 유추해볼 수 있다.nums[0] // 1 nums[1] // 2
Subscript 옵션
Subscript는 일반적인 메서드처럼 제공하는 옵션들이 있다.
📝 참고 사이트