我有以下代码:
(0...engine.rows-1).forEach {row in
(0...engine.cols-1).forEach {col in
//print("(\(row),\(col)) state = \(engine.grid[(row,col)])")
switch engine.grid[(row,col)] {
case CellState.empty: emptyCount = emptyCount + 1
case CellState.alive: aliveCount = aliveCount + 1
case CellState.died: diedCount = diedCount + 1
case CellState.born: bornCount = bornCount + 1
}
}
}
看起来过滤器可以更有效地执行此操作,但我不了解复杂对象的语法。如果没有过滤器,是否有更好的方法快速进行嵌套循环?
谢谢
答案 0 :(得分:3)
这看起来像Conway's Game of Life。
您正在遍历网格,对各种单元状态进行计数。嵌套循环是执行此操作的自然方法。我建议使用for in
而不是forEach
。另外,我建议创建一个字典来保存计数:
// Create dictionary to hold counts
var counts: [CellState : Int] = [.alive: 0, .died: 0, .born: 0, .empty: 0]
for row in 0 ..< engine.rows {
for col in 0 ..< engine.cols {
//print("(\(row),\(col)) state = \(engine.grid[(row,col)])")
counts[engine.grid[(row, col)]] += 1
}
}
另一种方式:
您未向我们提供有关您的Engine
class
或struct
的信息。根据{{1}}的实现,可能有一种获取所有单元格数组的方法。
例如,如果使用N-Dimensional Array创建grid
,则可以使用grid
将所有单元格作为数组。
grid.data
设置单元格状态如下:
struct Engine {
let rows: Int
let cols: Int
var grid: NDimArray<CellState>
init(rows: Int, cols: Int) {
self.rows = rows
self.cols = cols
self.grid = NDimArray<CellState>(dimensions: rows, cols, initial: CellState.empty)
}
}
然后计算单元格类型的代码变为:
var engine = Engine(rows: 20, cols: 20)
engine.grid[0, 0] = .alive
engine.grid[0, 1] = .alive