Update to Xcode 7.3 and get: unexpectedly found nil while unwrapping an Optional value [duplicate]

对着背影说爱祢 提交于 2019-12-10 12:33:28

问题


The following code works fine with Xcode 7.2.1. After I upgraded to 7.3 I get a crash with: "unexpectedly found nil while unwrapping an Optional value"

var backgroundMusic: SKAudioNode!

func playBackgroundMusic(name: String) {
  var delay = 0.0
  if backgroundMusic != nil {
    backgroundMusic.removeFromParent()
  } else {
delay = 0.1 }
  runAction(SKAction.waitForDuration(delay)) {
    self.backgroundMusic = SKAudioNode(fileNamed: name)
    self.backgroundMusic.autoplayLooped = true
    self.addChild(self.backgroundMusic)
} }

didMoveToView(view: SKView) {
...
playBackgroundMusic("Music.mp3")
}
  • I also tried cleaning the project, deleting all the Xcode Developer derived data, and verifying that the "Music.mp3" is being built into the main bundle.
  • Going back to Xcode 7.2.1 and building works fine with the same code.

Been scratching my head on this one most of the day. Is there a better way to do this?


回答1:


Try changing your variable declaration to an optional.

var backgroundMusic: SKAudioNode?

Then unwrap it as so:

if let bm = backgroundMusic {
  bm.removeFromParent()
} else {
  delay = 0.1 }
  runAction(SKAction.waitForDuration(delay)) {
  self.backgroundMusic = SKAudioNode(fileNamed: name)
  self.backgroundMusic.autoplayLooped = true
  self.addChild(self.backgroundMusic)
}



回答2:


try this.With temp constant

var backgroundMusic: SKAudioNode!

func playBackgroundMusic(name: String) {
  var delay = 0.0
  if backgroundMusic != nil {
    backgroundMusic.removeFromParent()
  } else {
  delay = 0.1
  runAction(SKAction.waitForDuration(delay)) {
    let temp = SKAudioNode(fileNamed: name)
    self.backgroundMusic = temp
    self.backgroundMusic.autoplayLooped = true
    self.addChild(self.backgroundMusic)
 } 
}

didMoveToView(view: SKView) {
...
playBackgroundMusic("Music.mp3")
}


来源:https://stackoverflow.com/questions/36273271/update-to-xcode-7-3-and-get-unexpectedly-found-nil-while-unwrapping-an-optional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!