我有Cell结构值(position:,state :),需要在我的Grid结构的init中设置,但我似乎无法设置Cell的这些值。
struct Cell {
var position: (Int,Int)
var state: CellState
init(_ position: (Int,Int), _ state: CellState) {
self.position = (0,0)
self.state = .empty
}
}
func positions(rows: Int, cols: Int) -> [Position] {
return (0 ..< rows)
.map { zip( [Int](repeating: $0, count: cols) , 0 ..< cols ) }
.flatMap { $0 }
.map { Position(row: $0.0,col: $0.1) }
}
我评论了我尝试将该职位设置为(row,col)的所有方式
struct Grid {
static let offsets: [Position] = [
(row: -1, col: 1), (row: 0, col: 1), (row: 1, col: 1),
(row: -1, col: 0), (row: 1, col: 0),
(row: -1, col: -1), (row: 0, col: -1), (row: 1, col: -1)
]
var rows: Int = 10
var cols: Int = 10
var cells: [[Cell]] = [[Cell]]()
init(_ rows: Int,
_ cols: Int,
cellInitializer: (Int, Int) -> CellState = { _,_ in .empty } ) {
self.rows
self.cols
self.cells = [[Cell]](repeatElement([Cell](repeatElement(Cell((0,0), .empty), count: cols)),count: rows))
positions(rows: rows, cols: cols).forEach { row, col in
// var position = cells(position: (row, col)) => cannot call value of non-function type '[[Cell]]'
// cells.position = (row, col) => value type of '[[Cell]] has no member position'
// cells.position(row, col) => value type of '[[Cell]] has no member position'
// position *= cells.position(row, col) => closure cannot implicitly capture a mutating self parameter
}
}
}
显然,Cell结构具有位置属性,为什么我无法访问它?
答案 0 :(得分:1)
这里的问题是您尝试访问cells.position
,但cells
是一个二维数组。
cells.position = (row, col) => value type of '[[Cell]] has no member position'
您可以遍历单元格并设置每个单元格的位置。
因此,在forEach
循环中,您可以改为编写
cells[row][column].position = (row, col)
那应该这样做。
答案 1 :(得分:1)
问题是你的所有行都没有实际访问Cell
结构的实例。
这是您的代码的功能调整。我允许自己删除似乎从代码库中遗漏的额外内容:
struct Cell {
var position: (Int,Int)
init(_ position: (Int,Int)) {
self.position = (0,0)
}
}
func positions(rows: Int, cols: Int) -> [(Int, Int)] {
return (0 ..< rows)
.map { zip( [Int](repeating: $0, count: cols) , 0 ..< cols ) }
.flatMap { $0 }
.map { ($0.0, $0.1) }
}
struct Grid {
var rows: Int = 10
var cols: Int = 10
var cells: [[Cell]] = [[Cell]]()
init(_ rows: Int, _ cols: Int) {
self.rows = rows
self.cols = cols
self.cells = Array.init(repeating: Array.init(repeating: Cell((0,0)), count: cols), count: cols)
positions(rows: rows, cols: cols).forEach { row, col in
cells[row][col].position = (row, col)
}
}
}
let g = Grid(1, 2)
print(g.cells[0][1].position)
现在,有关您遇到的错误的更详细说明:
var position = cells(position: (row, col))
在这里,您没有在任何单元格上设置任何内容。相反,您正在尝试调用您的网格,就像它是一个函数一样,参数为position: (Int, Int)
。
cells.position = (row, col)
您在这里尝试在矩阵(position
)上设置属性[[Cell]]
。显然,Swift抱怨内置类型Array
中不存在这样的属性。
cells.position(row, col)
您在此处尝试在矩阵(position
)上设置属性[[Cell]]
,并将其称为具有两个参数Int
的函数。问题与上述类似。
position *= cells.position(row, col)
我无法告诉您发生了什么,因为position
似乎没有在您的代码中声明。我想它来自你的代码库中的其他地方,或者它只是一个错字。