8

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?

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
AConsiglio
  • 256
  • 1
  • 3
  • 13

4 Answers4

5

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
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
4

You can also do it with this oneliner:

var foo = Array(repeating: Array(repeating: false, count: 10), count: 10)
Thein
  • 3,940
  • 2
  • 30
  • 34
Krzak
  • 1,441
  • 11
  • 12
3

For Swift 3.1:

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

See Swift documentation

vonox7
  • 1,081
  • 13
  • 24
0

As a one-liner, you can initialize like this with computed values assigned:

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 } }
Yoichi Tagaya
  • 4,547
  • 2
  • 27
  • 38