Subscript
Subscripts in Swift are shortcuts for accessing elements from a collection, list, or sequence. You can define subscripts to provide a more intuitive way to access data from your classes, structures, or enumerations, similar to how you would access elements in an array or dictionary.
Defining a Subscript
You define a subscript with the subscript keyword. Here's a basic 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])")
// Output: "Six times three is 18"
Subscript Options
Multiple Parameters: Subscripts can take multiple parameters.
struct Matrix {
let rows: Int
let columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
subscript(row: Int, col: Int) -> Double {
get {
return grid[(row * columns) + col]
}
set {
grid[(row * columns) + col] = newValue
}
}
}
Read-Only Subscripts: If a subscript is read-only, you can omit the get keyword for brevity.
struct FixedLengthRange {
var firstValue: Int
let length: Int
subscript(index: Int) -> Int {
return firstValue + index
}
}
Using Subscripts
Here's how you could use the Matrix subscript to set and get values:
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
let someValue = matrix[1, 0]
// someValue is 3.2
Type Subscripts
You can also define subscripts that are called on the type rather than on instances of the type. These are indicated by the static keyword.
enum Math {
static subscript(n: Int) -> Double {
return Double(n * n)
}
}
let value = Math[3] // value is 9.0
Overloaded Subscripts
You can provide more than one subscript implementation based on the number or types of the parameters. This is known as overloading.
struct Vector3D {
var x = 0.0, y = 0.0, z = 0.0
subscript(index: Int) -> Double? {
switch index {
case 0:
return x
case 1:
return y
case 2:
return z
default:
return nil
}
}
subscript(axis: String) -> Double? {
switch axis {
case "x":
return x
case "y":
return y
case "z":
return z
default:
return nil
}
}
}
var v = Vector3D()
v[0] = 3.0
v[1] = 2.0
v[2] = 1.0
print(v[0]) // Output: Optional(3.0)
print(v["y"]) // Output: Optional(2.0)
Subscripts provide a convenient syntax for accessing and modifying data, making your code more expressive and easier to understand. They offer an intuitive interface for working with collections, matrices, or any other data structures where elements need to be easily accessed.