无法在Swift中更改数组中引用对象的属性

时间:2014-10-20 12:23:41

标签: arrays swift reference

我正在尝试创建一个由20 * 20个图块组成的基于网格的地图,但是我无法使图块进行通信并访问相邻图块的属性。

这是尝试实现此目的的代码:

var tileArray:Array = []

class Tile:SKSpriteNode
{
    var upperAdjacentTile:Tile?

    override init()
    {
        let texture:SKTexture = SKTexture(imageNamed: "TempTile")
        let size:CGSize = CGSizeMake(CGFloat(20), CGFloat(20))

        super.init(texture: texture, color: nil, size: size)
    }

    required init(coder aDecoder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

    func setAdjacentTile(tile:Tile)
    {
        upperAdjacentTile = tile
    }
}

for i in 0..<10
{
    for j in 0..<10
    {
        let tile:Tile = Tile()
        tile.position = CGPointMake(CGFloat(i) * 20, CGFloat(j) * 20 )
        tile.name = String(i) + String(j)

        //checks if there is a Tile above it (aka previous item in array)
        if(i+j != 0)
        {
                                          //The position of this tile in array minus one
            tile.setAdjacentTile(tileArray[(j + (i * 10)) - 1] as Tile)
        }

        tileArray.append(tile)
    }
}

println(tileArray[10].upperAdjacentTile) //Returns the previous item in tileArray
println(tileArray[9].position) //Returns the position values of same item as above
println(tileArray[10].upperAdjacentTile.position) //However, this doesn't work

为什么我无法访问/更改“upperAdjacentTile”中引用的磁贴的属性?

1 个答案:

答案 0 :(得分:0)

upperAdjacentTile是一个可选项,您必须先解包(因为它可以是nil)。

// will crash if upperAdjacentTile is nil
println(tileArray[10].upperAdjacentTile!.position)

if let tile = tileArray[10].upperAdjacentTile {
    // will only run if upperAdjacentTile is not nil
    println(tile.position)
}

修改

正如rintaro建议你还必须指定数组包含的对象的类型:

var tileArray = [Tile]()