gpt4 book ai didi

variables - 如何初始化以变量作为参数的结构实例

转载 作者:行者123 更新时间:2023-11-30 10:21:35 25 4
gpt4 key购买 nike

我有一个结构:

struct Matrix {
let rows: Int, columns: Int
var grid: [Int]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Int {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}

我现在想在我的 GameScene 中创建一个实例:

class GameScene: SKScene {


let _numRows: CGFloat = 10
let _numCols: CGFloat = 10


var array = Matrix (rows: Int(_numCols), columns: Int(_numCols))
.....

错误:

'GameScene.Type' does not have a member named '_numCols'

那么如何使用常量作为参数创建 Matrix 实例?

最佳答案

字段的初始化可能不依赖于彼此。大概是因为初始化顺序是未定义的。将数组的初始化移至 init() 中:

var array: Matrix

init()
{
array = Matrix (rows: Int(_numCols), columns: Int(_numCols))
}

关于variables - 如何初始化以变量作为参数的结构实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26256606/

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