如何在Swift中声明多维布尔数组? [英] How to Declare a Multidimensional Boolean array in Swift?

查看:130
本文介绍了如何在Swift中声明多维布尔数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多关于如何做到这一点的不同例子,但它们似乎都没有显示出我真正需要的答案。所以我知道如何声明一个bool类型的多维数组。

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]] = []

但我无法弄清楚如何声明10 x 10的类型。我查找的每个例子都附加到一个空集,那么如何将这个变量初始化为10x10,其中每个点被认为是一个布尔值?

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?

推荐答案

其他答案有效,但你可以使用Swift泛型,下标和选项来制作一般类型的2D数组类:

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

用法:

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

这篇关于如何在Swift中声明多维布尔数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆