我有需要在我的網格結構的init中設置的Cell結構值(position :, state :),但我似乎無法設置Cell的這些值。Swift在另一個結構中設置一個結構值初始化
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) }
}
我評論了這一切,我試圖設置的位置(行,列)
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
}
}
}
顯然,細胞結構有位置的財產的方式,爲什麼能我可以訪問它嗎?
謝謝你的解釋。這非常有幫助! – HashRocketSyntax