Updated 1 July 2020
Subscripts are typically used as a shortcut for accessing the collection, sequence, and a list in Classes, Structures, and Enum without using a method. It used to store and retrieve the values without the use of separate methods. To access elements via this write one or more values between square brackets after the instance name. It can take any number of input parameters, and these input parameters can be of any type.
For a single type, subscripts can range from single to multiple declarations. We can use the appropriate subscript to overload the type of index value passed to the subscript.
1 2 3 4 5 6 7 8 9 |
subscript (<parameters>) -> <return type> { // the getter is required here get { // used for subscript value declarations here } set(newValue) { // the setter is optional // definitions are written here } } |
Consider the Matrix structure, which represents a two-dimensional matrix of Double values. It takes two integer parameters (rows and columns) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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, 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[(rows * column) + row] } set { if indexIsValid(row: row, column: column) { grid[(row * columns) + column] = newValue } else { print("Not valid") } } } } |
Matrix
is initialized by two parameters (rows and columns) and creates an array of size rows * columns to store double value. Initially, we store value for each index in the array is 0.
So, let’s create the Matrix instance by adding the row and column in the parameter of its initializer.
1 |
var matrix = Matrix(rows: 3, columns: 2) |
Now, the grid array form as:
1 2 3 4 5 6 7 8 |
grid: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] column 0 1 0 | 0.0 0.0 | row 1 | 0.0 0.0 | 2 | 0.0 0.0 | |
So, set the value of the Matrix by adding the row and column.
1 2 |
matrix[1, 0] = 1.5 matrix[2, 1] = 3.2 |
So, the grid array changed as:
1 2 3 4 5 6 7 8 |
grid: [0.0, 0.0, 1.5, 0.0, 0.0, 3.2] column 0 1 0 | 0.0 0.0 | row 1 | 1.5 0.0 | 2 | 0.0 3.2 | |
The Matrix
subscript’s getter and setter and both have checked the assertion that the subscript’s rows and columns values are valid. Because in some cases it can be out of the index.
1 2 3 |
func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } |
So if you have any comments, questions, or recommendations, feel free to post them in the comment section below!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.