Swift在另一个结构初始化中设置结构值

Swift在另一个结构初始化中设置结构值,swift,struct,initialization,Swift,Struct,Initialization,我有单元格结构值(位置:,状态:),需要在网格结构的init中设置,但我似乎无法设置单元格的这些值 struct Cell { var position: (Int,Int) var state: CellState init(_ position: (Int,Int), _ state: CellState) { self.position = (0,0) self.state = .empty } } func positi

我有单元格结构值(位置:,状态:),需要在网格结构的init中设置,但我似乎无法设置单元格的这些值

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) }
}

很明显,Cell结构有一个position属性,那么为什么我不能访问它呢?

这里的问题是您正在尝试访问
单元格。position
但是
单元格
是一个二维数组

cells.position = (row, col)  => value type of '[[Cell]] has no member position'
您可以在单元格中循环并设置每个单元格的位置

因此,您可以在
forEach
循环中编写代码

cells[row][column].position = (row, col)

这应该可以做到。

问题是,没有一行实际访问
单元格
结构的实例

下面是对代码的功能性修改。我允许自己删除代码库中似乎遗漏的额外内容:

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)
在这里,你不能在任何单元格上设置任何内容。相反,您试图调用网格,就像调用函数一样,使用参数
position:(Int,Int)

在这里,您试图在矩阵(
[[Cell]]
)上设置属性
位置。显然,Swift抱怨其内置类型
数组中不存在此类属性

cells.position(row, col)
在这里,您试图在矩阵(
[[Cell]]
)上设置一个属性
位置
,并将其作为具有两个参数
Int
的函数调用。问题与上述类似

position *= cells.position(row, col)

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

谢谢您的解释。那很有帮助!谢谢你,这就是我要说的。那么[row]访问数组的第一层,而[column]访问第二层吗?
cells.position = (row, col)
cells.position(row, col)
position *= cells.position(row, col)