Subscript Definition in Swift

Level 5422 keystrokes

Matrix keeps its data private and exposes it through a subscript with two indices. The initializer fills a rows × cols grid with zeros, the code sets four cells and prints m[1,1] = 4.

Swift code

1struct Matrix {
// private: only accessible inside Matrix, so outside code uses the subscript
2 private var data: [[Int]]
// Two constants declared on one line
3 let rows: Int, cols: Int
4
5 init(rows: Int, cols: Int) {
6 self.rows = rows
7 self.cols = cols
// Builds rows arrays, each holding cols zeros
8 data = Array(repeating: Array(repeating: 0, count: cols), count: rows)
9 }
10
// Subscript with two parameters, used as m[row, col]
11 subscript(row: Int, col: Int) -> Int {
// Getter: reads one cell
12 get { return data[row][col] }
// Setter: writes newValue into the cell
13 set { data[row][col] = newValue }
14 }
15}
16
// A 2 × 2 matrix of zeros; var so the setter can modify it
17var m = Matrix(rows: 2, cols: 2)
// Each assignment calls the setter
18m[0, 0] = 1
19m[0, 1] = 2
20m[1, 0] = 3
21m[1, 1] = 4
// Calls the getter: prints m[1,1] = 4
22print("m[1,1] = \(m[1, 1])")

Output

m[1,1] = 4
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.

  • :× 13
  • ,× 12
  • [× 12
  • ]× 12
  • =× 10
  • (× 7
  • )× 7
  • {× 5
  • }× 5
  • .× 2

More Swift examples at level 5

← Swift typing practice