목차
- Subscript Syntax
- Subscript Usage
- Type Subscripts
Subscripts
Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.
(subscript - 컬렉션, 리스트, 시퀀스의 멤버 엘리먼트에 접근하기 위한 shortcut을 제공)
ex) someArray[index], someDictionary[key], ...
1. Subscript Syntax
- subscripts can be read-write or read-only.
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action here.
}
}
2. Subscript Usage
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
3. 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)
Ref.
https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html
'iOS > Swift' 카테고리의 다른 글
[Swift 5.2] Methods - Apple Documentation (0) | 2020.03.05 |
---|---|
[Swift] ExpressibleByStringLiteral, CustomStringConvertible (0) | 2020.02.18 |
[Swift4.1] map, flapMap, compactMap (0) | 2019.12.11 |
[Swift 5.2] Properties - Apple Documentation (0) | 2019.12.08 |
[Swift5.1] Overview (0) | 2019.12.04 |