如何使用变量作为参数初始化Structure的实例

时间:2014-10-08 12:11:55

标签: variables parameters swift

我有一个结构:

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实例中创建?

1 个答案:

答案 0 :(得分:1)

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

var array: Matrix

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