gpt4 book ai didi

Swift 在另一个 struct init 中设置一个 struct 值

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:12 26 4
gpt4 key购买 nike

我有 Cell 结构值 (position:, state:) 需要在我的 Grid 结构的初始化中设置,但我似乎无法设置 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) }
}

我已经评论了我尝试将位置设置为(行,列)的所有方式

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 结构具有位置属性,为什么我不能访问它?

最佳答案

问题是您的代码行实际上都没有访问您的 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)

在这里,您尝试在矩阵 ([[Cell]]) 上设置属性 position。显然,Swift 提示说它的内置类型 Array 中不存在这样的属性。

cells.position(row, col)

在这里,您尝试在矩阵 ([[Cell]]) 上设置属性 position 并将其作为具有两个参数 Int 的函数调用。问题同上。

position *= cells.position(row, col)

在这里我不知道发生了什么,因为 position 似乎没有在您的代码中声明。我猜它来自您的代码库中的其他地方,或者它可能只是一个拼写错误。

关于Swift 在另一个 struct init 中设置一个 struct 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com