2016-12-01 99 views
0

我試圖播放基於文件名的聲音。我用所有文件名創建了一個枚舉。一切正常,但這種情況下,我在那裏檢查了soundType.clickSwift 3枚舉函數導致應用程序崩潰

func playSound(type: soundType) { 
    var soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!) 
    if type.rawValue == soundType.click.rawValue { 
     soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "wav")!) 
    } 
    do { 
     audioPlayer = try AVAudioPlayer(contentsOf: soundUrl) 
     audioPlayer.play() 
    } catch _ { } 
} 

這裏是我的枚舉

enum soundType: String { 
    case selectAnswer = "answerSelected" 
    case correctAnswer = "correctAnswer" 
    case wrongAnswer = "wrongAnswer" 
    case click = "click" 
} 

的問題是在這裏,我檢查「type.rawValue == soundType。 click.rawValue」

以下是錯誤

fatal error: unexpectedly found nil while unwrapping an Optional value 
+0

那麼,程序發現零,意外的是,雖然它是......解開一個'可選的'值:P這正是它在調用URL.init之前所說的 – Alexander

回答

3

你應該看看這行代碼第一。

var soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!) 
soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "wav")!) 

在這裏,你力展開一個failable初始化。您應該檢查是否Bundle.main.path(forResource: type.rawValue, ofType: "aiff")!)通過做這樣的事情存在第一...

if let soundUrl = URL.init(fileURLWithPath: Bundle.main.path(forResource: type.rawValue, ofType: "aiff")){ 
     if type.rawValue == soundType.click.rawValue { 
      ... 
    } 

,或者您也可以使用保護聲明..

檢查這個博客帖子由Natashtherobot更多地瞭解如何解開的東西好。 https://www.natashatherobot.com/swift-guard-better-than-if/

+1

,請檢查Bundle.main.path( forResource:type.rawValue,ofType:「aiff」)'這也應該是nil – Cruz

+0

Bundle有一個名爲URLForResource的方法,一路走來沒有任何意義 –