解包可选值

时间:2016-07-06 20:09:33

标签: swift sprite-kit

正如标题所说,在**线上发生致命错误。不知道它怎么可能是零?它只发生在如此多的戏剧之后。也许是因为它从数组中获取声音文件?在didBeginContact函数中每隔一次蓝色月亮也会发生。

var soundFiles = ["gary1", "gary2","gary3","gary4","gary5","gary6","gary7","gary8","gary9","gary10","gary11","gary12","gary13","gary14",]
var audioPlayer: AVAudioPlayer = AVAudioPlayer()

func setupAudioPlayer(file: NSString, type: NSString){
        let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
        **let url = NSURL.fileURLWithPath(path!)**
        do {
            try  audioPlayer = AVAudioPlayer(contentsOfURL: url)
        }
        catch {
            print("Player not available")
        }
    }



func playRandomSound() {
        let range: UInt32 = UInt32(soundFiles.count)
        let number = Int(arc4random_uniform(range))

        self.setupAudioPlayer(soundFiles[number], type: "mp3")

        self.audioPlayer.play()
    }
}

func didBeginContact(联系方式:SKPhysicsContact){

// 1
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
  firstBody = contact.bodyA
  secondBody = contact.bodyB
} else {
  firstBody = contact.bodyB
  secondBody = contact.bodyA
}

// 2
if ((firstBody.categoryBitMask & PhysicsCategory.Monster != 0) &&
    (secondBody.categoryBitMask & PhysicsCategory.Projectile != 0)) {
 *** projectileDidCollideWithMonster(firstBody.node as! SKSpriteNode, monster: secondBody.node as! SKSpriteNode)**
}

1 个答案:

答案 0 :(得分:1)

当代码有时只工作而其他代码不工作时,我建议使用guard语句防止强制解包,以查看代码失败的条件。要重写您遇到问题的两种方法:

func setupAudioPlayer(file: String, type: String){
    guard let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type ) else {
        print("Failed to get path – file: \(file) type: \(type)")
        return
    }
    let url = NSURL.fileURLWithPath(path)
    do {
        try  audioPlayer = AVAudioPlayer(contentsOfURL: url)
    }
    catch {
        print("Player not available")
    }
}

这样,只有在您确定路径不是nil时,代码才会继续。

同样,您也可以使用guard语句尝试调试第二个问题。以下是更新的if语句的示例:

if ((firstBody.categoryBitMask & PhysicsCategory.Monster != 0) &&
(secondBody.categoryBitMask & PhysicsCategory.Projectile != 0)) {
    guard let firstNode = firstBody.node as? SKSpriteNode, let secondNode = secondBody.node as? SKSpriteNode else {
        print("Could not Cast nodes. FirstNode Type: \(firstBody.node.dynamicType) SecondNode type: \(secondBody.node.dynamicType)")   
        return
    }
    projectileDidCollideWithMonster(firstBody.node as! SKSpriteNode,      monster: secondBody.node as! SKSpriteNode)
 }

如果您有任何疑问,请与我联系!