I've seen so many different examples on how to do this but none of them seem to show an answer that I really need. So I know how to declare a multidimensional array of type bool.
var foo:[[Bool]] = []
However I cannot figure out how to declare this of type 10 x 10. Every example I look up just appends to an empty set, so how do I initialize this variable to be a 10x10 where each spot is considered a boolean?
Multidimensional array means array of arrays. That is each element of an array is also an array. Let’s take a look how to create multidimensional array in swift :
Declaring an array in Swift is quite easy, and it then allows all the elements and values to get accessed and manipulated easily. There are two ways to declare an array which are as follows: One way is to initialize the variable with an empty array. Another way is to use the automatic type inference.
Swift Boolean Tutorial 1 Swift Bool. In Swift, Bool is a frozen structure, whose instances are either true or false. ... 2 Declare Boolean Variable. ... 3 Initialize Boolean Variable. ... 4 Logical Operations. ... 5 Boolean Value in Conditional Statements. ... 6 Conclusion. ...
But, what if we want to store multiple values of the same data type. We use something called Array in Swift. An array is simply a container that can hold multiple data (values) of a data type in an ordered list, i.e. you get the elements in the same order as you defined the items in the array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With