2014-10-20 2 views
1

20 * 20 타일로 만든 격자 기반지도를 만들려고하지만 타일을 통신하고 인접한 타일의 속성에 액세스하는 데 문제가 있습니다.Swift에서 배열의 참조 된 객체의 속성을 변경할 수 없습니다.

이 사용 된 코드는 이러한 목표를 달성하기 위해 노력하고있다 :

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"에서 참조 타일의 속성을 변경?

답변

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

편집

제안으로 :

var tileArray = [Tile]() 
+0

오류 읽기 "를 타일 않습니다 Tile이 SKSpriteN의 하위 클래스 임에도 불구하고 'position'이라는 멤버가 없습니다. 송시. Codehints는 심지어 나를 '위치'로 자동 완성하므로, 나에게 의미가 없습니다. – user3368104

+0

@ user3368104'var tileArray : Array = []'과 같이 배열의 타입을 명시 적으로 정의해야합니다. – rintaro

관련 문제