gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:18:23 25 4
gpt4 key购买 nike

我正在尝试创建一个由 20*20 的图 block 组成的基于网格的 map ,但我无法让这些图 block 相互通信并访问相邻图 block 的属性。

这是用于实现此目的的代码:

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”中引用的图 block 的属性?

最佳答案

upperAdjacentTile 是一个 Optional,你必须先打开它(因为它可以是 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]()

关于arrays - 无法在 Swift 中更改数组中引用对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465650/

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