2017-10-04 40 views
-1

我是新来的迅速和我从Udemy的课程学习。斯威夫特:解包无导致我的程序崩溃

,我发现了错误

“主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子码=为0x0)”

和控制台解释为 “意外发现零而展开的可选值”。

我双重检查,以确保我的代码是完全相同作为我的教练的,甚至重新启动一次的情况下,我搞砸的东西了,但我仍然得到同样的错误。

我的代码如下:

import UIKit 
    import AVFoundation 

    class ViewController: UIViewController { 
     @IBOutlet weak var darkBlueBG: UIImageView! 
     @IBOutlet weak var powerButton: UIButton! 
     @IBOutlet weak var cloudHolder: UIView! 
     @IBOutlet weak var rocket: UIImageView! 
     @IBOutlet weak var hustleLbl: UILabel! 
     @IBOutlet weak var onLbl: UILabel! 

     var player: AVAudioPlayer! 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav")! //This is the line that the console says is causing the error 
      let url = URL(fileURLWithPath: path) 

      do { 
       player = try AVAudioPlayer(contentsOf: url) 
       player.prepareToPlay() 
      } catch let error as NSError { 
       print(error.description) 
      } 
     } 


     @IBAction func powerButtonPressed(_ sender: Any) { 
      cloudHolder.isHidden = false 
      darkBlueBG.isHidden = true 
      powerButton.isHidden = true 

      player.play() 

      UIView.animate(withDuration: 2.3, animations: { 
      self.rocket.frame = CGRect(x: 0, y: 20, width: 375, height: 402) 
      }) { (finished) in 
       self.hustleLbl.isHidden = false 
       self.onLbl.isHidden = false 

      } 
     } 
    } 
+4

每次使用'!'斯威夫特,你说一次“我想如果有什么错我的代码在这里崩溃”。 –

+0

@rmaddy我不确定这个愚蠢的标志是有帮助的。 OP的问题不是“我不明白什么解开nil的意思”,而是“我的代码和我的老师的代码是一样的,为什么我的老师没有时我的失败? –

回答

0

根据您所举报的线,它看起来像hustle-on.wav不包括在你的包资源文件。仔细检查你的项目中是否有这个文件。如果这样做,请选择它并查看文件检查器,然后仔细检查是否检查了目标。

+0

目标未被检查,谢谢 – Steven

2

请阅读path方法的文档:

https://developer.apple.com/documentation/foundation/bundle/1409670-path

它指出,这种方法可以返回nil

返回值

的完整路径名的资源文件,或者零如果 文件无法找到。

所以,你应该通过使用guard要么展开可选或为了防止崩溃使用if let采取适当的预防措施。

例如:

if let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav") { 
    // work with the path value 
} else { 
    // take appropriate action since path is nil! 
} 

guard 
    let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav") else{ 
     // take appropriate action since path is nil! 
     return 
    } 
0

你不应该解开一个可选的那样,而是使用保护或者让如下:

guard let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav") else { 
    // Add some logic here because the file wasn't found. Then return because it failed. 
    return 
} 

if let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav") { 
    let url = URL(fileURLWithPath: path) 

    do { 
     player = try AVAudioPlayer(contentsOf: url) 
     player.prepareToPlay() 
    } catch let error as NSError { 
     print(error.description) 
    } 
} 

那么它只会尝试使用路径,如果它来自于Bundle.main.path回电。