Subscript in Swift

Level 4224 keystrokes

Matrix defines a two-argument subscript with get and set, so elements can be read and written as m[row, col]. It prints 2 and then 10 after the assignment.

Swift code

1struct Matrix {
// Rows of a 2D grid stored as an array of arrays
2 var grid: [[Int]]
3
// A subscript can take several parameters: m[row, col]
4 subscript(row: Int, col: Int) -> Int {
// Runs when reading m[row, col]
5 get {
6 return grid[row][col]
7 }
// Runs when assigning to m[row, col]; newValue is the assigned value
8 set {
9 grid[row][col] = newValue
10 }
11 }
12}
13
// var is needed because the setter modifies the struct
14var m = Matrix(grid: [[1, 2], [3, 4]])
// Row 0, column 1: prints 2
15print(m[0, 1])
// Calls the setter: replaces 3 with 10
16m[1, 0] = 10
// Prints 10
17print(m[1, 0])

Output

2
10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • [× 12
  • ]× 12
  • ,× 7
  • :× 4
  • (× 4
  • )× 4
  • {× 4
  • }× 4
  • =× 3
  • -× 1

More Swift examples at level 4

← Swift typing practice