Subscripts shortcut for accessing the member elements in a collection, list, or sequence. Implement subscripts in the most appropriate way for your particular class or structure’s functionality.
Subscripts to set and retrieve values by index without needing separate methods for setting and retrieval.
subscripts can be read-write or read-only.
implement subscript using subscript keyword.
syntax :
subscript(index: Int) -> Int {
get {
// Return an appropriate subscript value here.
}
set(newValue) {
// Perform a suitable setting action 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])")
subscripts can’t use in-out parameters.
Multiple subscripts can be defined for a single type and subscripts can have multiple input parameters.
example :
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
}
}
}
- Type Subscripts - subscripts defined on the type itself. Use static for struct and enum, and class for class to enable overriding.
example :
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)
Top comments (0)