arrays - Swift 中的 3x3 数组

标签 arrays swift

<分区>

我试图在 Swift 中制作一个 3x3 数组,但行数总是与我预期的不同。例如,我认为下面的代码会生成一个 3x3 数组,但实际上是 9x3 数组。为什么?我怎样才能让它变成 3x3?

var NumColumns = 3
var NumRows = 3
var occupied = [[Bool]](count: NumColumns, repeatedValue:[Bool](count: NumRows, repeatedValue:false));
for item in occupied {
    for item in occupied {
        print(item)
    }
}

最佳答案

看起来您需要一个 3x3 bool 值矩阵

然后您可以使用 Swift Programming Language 提供的(稍微更新的)代码作为示例.

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Bool]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: false)
    }
    func indexIsValidForRow(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Bool {
        get {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

例子

var matrix = Matrix(rows: 3, columns: 3)
matrix[0, 0] = true
print(matrix[0, 0]) // true

关于arrays - Swift 中的 3x3 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645272/

相关文章:

swift - 如何帮助 Vapor 成功地与我的 PostgreSQL 服务器进行 SSL 握手?

swift - 时间戳事件匹配错误: Failed to find matching element

ios - 更改 UISearchController 的 UINavigationBar 背景色

c++ - 为什么 (&array)[i] 不取第 i 个元素的地址?

javascript - 为什么这么多 Array.prototype(迭代)方法这么慢?

python - 使用索引数组对切片列表求和

ios - 在 Swift 子类中添加便利构造器

php - 通过重定向 PHP 发送数组

php - php通过其值之一合并两个或多个ArrayIterators

swift - Swift 2.2 上的可选绑定(bind)错误?