我在尝试将farmTile设为可选时出现此错误:可选类型的值Bool?不是unwrapped;是否要使用'!'或'?'?
一小时前还不错。

var farmTile:SKSpriteNode!

func createFarmTile(){

    farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    farmTile?.size = CGSize(width: 185, height: 195)
    farmTile?.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile!)
    farmTile?.name = "farmTile"
    farmTile.zPosition = 1

   if farmTile?.contains(touchLocation){
       print("test")
   }
}

最佳答案

farmTile?.contains(touchLocation)返回一个可选Bool。你应该正确地处理这个选项。做这样的事。。。

var farmTile: SKSpriteNode? // optional

func createFarmTile(){

    guard let farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    else { /* do what you need to do if it is missing */ ; return }

    farmTile.size = CGSize(width: 185, height: 195)
    farmTile.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile)
    farmTile.name = "farmTile"
    farmTile.zPosition = 1
    self.farmTile = farmTile

    if farmTile.contains(touchLocation){
       print("test")
    }
}

10-08 08:07