How to declare a multidimensional boolean array in Swift?

I have seen so many different examples on how to do this, but none of them seem to give the answer that I really need. Therefore, I know how to declare a multidimensional array of type bool.

var foo:[[Bool]] = []

However, I cannot figure out how to declare it as a 10 x 10 type. Each example that I look at is simply added to an empty set, so how to initialize this variable as 10x10, where each spot is considered a logical one?

+4
source share
4 answers

Other answers work, but you can use the Swift, subscriptip, and optionsals generators to create a typically typed class of 2D arrays:

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

( struct, mutating.)

:

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
+6

oneliner:

var foo = Array(count:10, repeatedValue:
                          Array(count:10, repeatedValue:false))
+1

As a single line, you can initialize it like this using the assigned values:

var foo = (0..<10).map { _ in (0..<10).map { $0 % 2 == 0 } }

or

var bar = (0..<10).map { a in (0..<10).map { b in (a + b) % 3 == 0 } }
0
source

For Swift 3.1:

var foo: [[Bool]] = Array(repeating: Array(repeating: false, count: 10), count: 10)

See Swift documentation

0
source

All Articles