函数中的Swift 3枚举会导致应用崩溃

时间:2016-12-01 01:58:31

标签: swift enums swift3

我试图根据文件名播放声音。我创建了一个包含所有文件名的枚举。一切正常,除了这种情况,我检查soundType.click

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

1 个答案:

答案 0 :(得分: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")!)

在这里,你强行展开一个可用的初始化程序。您应首先通过执行此类操作来检查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/