简体   繁体   English

如何在 Swift 中声明一个多维布尔数组?

[英]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.所以我知道如何声明一个 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?但是,我无法弄清楚如何声明 10 x 10 类型的这个。我查找的每个示例都只是附加到一个空集,那么如何将此变量初始化为 10x10,其中每个点都被视为布尔值?

The other answers work, but you could use Swift generics, subscripting, and optionals to make a generically typed 2D array class:其他答案有效,但您可以使用 Swift 泛型、下标和可选项来创建通用类型的 2D 数组类:

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 .) (你也可以把它变成一个结构体,声明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

你也可以用这个oneliner做到这一点

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

For Swift 3.1:对于 Swift 3.1:

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

See Swift documentation查看Swift 文档

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM