Swift 3枚举函数导致应用程序崩溃

问题描述:

我试图播放基于文件名的声音。我用所有文件名创建了一个枚举。一切正常,但这种情况下,我在那里检查了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

你应该看看这行代码第一。

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的方法,一路走来没有任何意义 –