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?

1
  • You can already store a 10x10 Bool inside that multidimensional array Commented Mar 6, 2015 at 3:33

4 Answers 4

5

You can also do it with this oneliner:

var foo = Array(repeating: Array(repeating: false, count: 10), count: 10)
Sign up to request clarification or add additional context in comments.

1 Comment

I'd set the repeatedValue to true or false explicitly.
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

Comments

4

For Swift 3.1:

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

See Swift documentation

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.