2016-12-01 15 views
0

ファイル名に基づいてサウンドを再生しようとしています。すべてのファイル名を持つ列挙型を作成しました。私は「type.rawValue == soundTypeをチェックするところすべてがこのような場合を除いて、動作しますが、私はsoundType.click機能のSwift 3 enumが原因でアプリケーションがクラッシュする

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" 
} 

という問題がここにあります。 click.rawValue」

ここでは、あなたがこのコード行を見てみる必要がありますエラー

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

'Optional'値をアンラップしている間、プログラムは予期せずnilを見つけました: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

バンドルにはURLForResourceというメソッドがあります。 –

関連する問題