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 subscript2 private var data: [[Int]] // Two constants declared on one line3 let rows: Int, cols: Int4 5 init(rows: Int, cols: Int) {6 self.rows = rows7 self.cols = cols // Builds rows arrays, each holding cols zeros8 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 cell12 get { return data[row][col] } // Setter: writes newValue into the cell13 set { data[row][col] = newValue }14 }15}16 // A 2 × 2 matrix of zeros; var so the setter can modify it17var m = Matrix(rows: 2, cols: 2)// Each assignment calls the setter18m[0, 0] = 119m[0, 1] = 220m[1, 0] = 321m[1, 1] = 4// Calls the getter: prints m[1,1] = 422print("m[1,1] = \(m[1, 1])")Output
m[1,1] = 4
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