How to Declare a Multidimensional Boolean array in Swift?
The other answers work, but you could use Swift generics, subscripting, and optionals to make a generically typed 2D array class:
class Array2D<T> {
let columns: Int
let rows: Int
var array: Array<T?>
init(columns: Int, rows: Int) {
self.columns = columns
self.rows = rows
array = Array<T?>(count:rows * columns, repeatedValue: nil)
}
subscript(column: Int, row: Int) -> T? {
get {
return array[(row * columns) + column]
}
set(newValue) {
array[(row * columns) + column] = newValue
}
}
}
(You could also make this a struct, declaring mutating
.)
Usage:
var boolArray = Array2D<Bool>(columns: 10, rows: 10)
boolArray[4, 5] = true
let foo = boolArray[4, 5]
// foo is a Bool?, and needs to be unwrapped
You can also do it with this oneliner:
var foo = Array(repeating: Array(repeating: false, count: 10), count: 10)
For Swift 3.1:
var foo: [[Bool]] = Array(repeating: Array(repeating: false, count: 10), count: 10)
See Swift documentation