Last active
March 29, 2021 03:50
-
-
Save maximbilan/cf6f015b1cdfa2df4894 to your computer and use it in GitHub Desktop.
Multidimensional arrays in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Array2D<T> { | |
var columns: Int | |
var rows: Int | |
var matrix: [T] | |
init(columns: Int, rows: Int, defaultValue: T) { | |
self.columns = columns | |
self.rows = rows | |
matrix = Array(count: columns * rows, repeatedValue: defaultValue) | |
} | |
subscript(column: Int, row: Int) -> T { | |
get { | |
return matrix[columns * row + column] | |
} | |
set { | |
matrix[columns * row + column] = newValue | |
} | |
} | |
func columnCount() -> Int { | |
return self.columns | |
} | |
func rowCount() -> Int { | |
return self.rows | |
} | |
} | |
// Using | |
let array = Array2D(columns: 5, rows: 5, defaultValue: 0) | |
array[0, 0] = 5 | |
array[1, 1] = 8 | |
array[2, 3] = 7 | |
for (var i = 0; i < 5; ++i) { | |
for (var j = 0; j < 5; ++j) { | |
print(array[i, j]) | |
} | |
} |
I feel like you used to work on C#.
Actually not 😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I feel like you used to work on C#.