Subscript functionality can be defined within a class, struct, or enum, or declared within a protocol as a requirement. To do this, we define subscript (which is a reserved keyword that activates the functionality) with input parameters and an output type:
subscript(row: Int, column: Int) -> GridPosition
This subscript definition works like a computed property, where get can be defined to allow you to access values through subscript, and set can be defined to assign values using subscript:
subscript(row: Int, column: Int) -> GridPosition {
get {
return gridStorage[row][column]
}
set(newValue) {
gridStorage[row][column] = newValue
}
}
Any number of input parameters can be defined, and these should be provided as comma-separated values in the subscript:
game[1, 2] = .player2 // Assigning a value
let topLeft = game[0, 0] // Accessing a value