展开可选错误时意外发现nil

时间:2019-03-30 05:22:36

标签: swift

我正在制作基于Sprite的游戏。在将物理应用于我的硬币精灵时,我已经开始遇到这个错误。关于如何避免这种情况有什么建议吗?

@objc func spawnEnemy(){
    enemy = childNode(withName: "enemy") as? SKSpriteNode
    coin = childNode(withName: "coin") as? SKSpriteNode
    self.physicsWorld.contactDelegate = self

及以后的

 for coin in sprites{
    if coin.name == "coin"{
        coin.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
        coin.physicsBody?.categoryBitMask = PhysicsCategory.coin
          coin.physicsBody?.contactTestBitMask =           PhysicsCategory.player
        coin.physicsBody?.affectedByGravity = false
        coin.physicsBody?.isDynamic = true
        }
}

1 个答案:

答案 0 :(得分:0)

您应该始终使用“ if let”或“ guard let”安全地解开可选值

使用if let:

   if let coin = coin , let name = coin.name { 
    // you can use "coin" or "name" safely here
   }else{
     // "coin" or "name" is nil
   }

通过使用警卫队让:

   guard let coin = coin , let name = coin.name  else { 
     // "coin" or "name" is nil
    return
    }
    //you can use "coin" or "name" safely here