Swift 3.0 subscript for basic learning
- 2020-05-24 06:17:57
- OfStack
preface
Classes, structs, and enums can all define subscripts that provide quick access to data member elements of a collection, list, or sequence. You can use
someArray[index]
To access Array, use
someDictionary[key]
Come visit Dictionary.
One type can define multiple subscripts.
Define 1 subscript of get set:
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
Define a subscript of read-only
subscript(index: Int) -> Int {
// return an appropriate subscript value here
}
Example:
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"
You can also use multiple subscripts of any type, except for parameters of type in-out
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
}
}
}
English text:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305
conclusion