是否有一行等效的 Java 代码用于创建二维数组:
cells = new Cell[width][height];
在Swift 2.0中?
查看 Stack Overflow 中的各种解决方案,我最终得到了一个多行怪物:
self.cells = [[Cell]]()
for (var col=0; col<height; col++){
var newColumn = Array<Cell>.init(count: width, repeatedValue: Cell(x: 0,y: 0))
self.cells.append(newColumn);
}
这为我创建了一个空数组。但我很确定这不是正确的解决方案,只是一种管道胶带的解决方法。
最佳答案
无需使用循环:
let inner = Array<Cell>(count: width, repeatedValue: Cell(x: 0,y: 0))
let cells = Array<[Cell]>(count: height, repeatedValue: inner)
当然,这可能是一句俏话:
let cells = Array<[Cell]>(count: height, repeatedValue: Array<Cell>(count: width, repeatedValue: Cell(x: 0,y: 0)))
但为了可读性,我更喜欢单独的语句。
关于arrays - 如何在 Swift 2 中初始化二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32735853/