Class, Struct, enum 들은 member elements에 바로 접근하는 SubScripts를 정의할 수 있다. 우리가 사용하는 Array[index] 나 Dictionary[Key] 또한 SubScript이다.
Subscript Syntax
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
- Subscript의 구문은 instance method와 computed property 구문과 매우 비슷함.
- 사용법은 subscript 키워드를 선언하고, 하나 또는 하나 이상(ex. 행렬)의 매개변수와 반환 타입을 지정한다.
- 인스턴스 메소드와는 달리 Subscripts는 read-write 나 read-only가 될 수 있다.
- read-only일 경우 get의 생략이 가능하다.
- 또한 한 오브젝트에 여러 가지 subscript 구문을 작성할 수 있다.(Overloading).
Type Subscripts
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)
앞에서 Subscript의 구문은 instance method, computed property와 매우 유사하다고 언급했다. 따라서 Subscript 또한 Type Method 와 Type Property와 마찬가지로 Type Subscript로 선언이 가능하다. Static으로 Subscript를 선언하면 객체가 생성되지 않고도 호출이 가능하다. 또한 Static으로 선언할 경우 Static Dispatch가 되기 때문에 오버라이딩이 불가능하고, Class로 선언할 경우 Dynamic Dispatch가 되기 때문에 오버라이딩이 가능하다.
Subscripts Usage
- Subscript는 Method를 사용하지 않고 Class, Struct, enum에 있는 Collection, Sequence 및 List의 정보에 액서스 하는 데 사용된다.
- 특별한 메소드 없이 인덱스를 사용해서 값을 저장하고 검색하는 데 사용할 수 있어 편리함.
참고자료
Subscripts — The Swift Programming Language (Swift 5.6)
Subscripts Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for se
docs.swift.org
Subscripts in swift
Subscripts are used to access information from a collection, sequence and a list in Classes, Structures and Enumerations without using a…
abhimuralidharan.medium.com
'Swift > 학습' 카테고리의 다른 글
Existential any in Swift explained with code examples(번역) (0) | 2023.04.06 |
---|---|
Swift Opaque Types(번역) (0) | 2023.03.28 |
enum으로 특정 단위를 명확하게 표현하기 (0) | 2022.09.25 |
2022 WWDC Embrace Swift Generics (1) | 2022.07.04 |
Protocol Optional Function (0) | 2022.04.14 |