Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Declare a Multidimensional Boolean array in Swift?

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?

like image 324
AConsiglio Avatar asked Mar 06 '15 03:03

AConsiglio


People also ask

What is multidimensional array in Swift?

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 :

How to declare an 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.

How do you use Boolean in Swift?

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. ...

How to store multiple values of the same data type in Swift?

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.


1 Answers

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
like image 65
Aaron Brager Avatar answered Oct 05 '22 12:10

Aaron Brager