2016-11-24 45 views
0

我剛纔已經升級,從斯威夫特2至3斯威夫特,又面臨着新的挑戰IM ...Swift3:意外發現零而展開的可選值

我有這之前完美運行的球員,但現在我有此以下問題:「意外發現零而展開的可選值」

這裏是我的代碼:

print(audioselectionne) 

let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: audioselectionne as String, ofType: "mp3")!) 

我已經得到了:可選(「鐵斯托」)和崩潰......

我真的不明白問題在哪裏...

感謝您的幫助。

+2

問題是你強制解開'pathForResource'的返回,但它是零;該資源未找到。 – Paulw11

+0

是的,但我沒有改變任何東西,它與Swift 2一起工作 – user2971617

+0

爲什麼你有倒下的'as String'?刪除。 – Paulw11

回答

0

我認爲Bundle.main.path方法返回一個可選String。如果這是nil(因爲找不到資源),強制解包會導致錯誤。如果你要正確地處理它,你必須檢查爲nil

guard let path = Bundle.main.path(…) else { 
    // resource not found, handle error 
} 

// now `path` is guaranteed to be non-nil 
let alertSound = URL(fileURLWithPath: path) 
+0

問題是爲什麼用Swift3,它沒有找到該文件?這很奇怪 – user2971617

+1

也許這個路徑與你之前在Swift 3中的代碼不同,但是你得到的錯誤是由解壓('!')引起的。除非你喜歡,否則不要強制展開值。 – zoul

+0

實際上,如果這應該在Bundle.main.path中,那麼您不應該處理該錯誤,而是修復該路徑或確保該資源在那裏。 – gnasher729

1

你應該解開可選,或許與可選的約束力。

順便說一句,你不應該再使用路徑字符串了。請直接使用網址,例如

guard let resource = audioselectionne, let alertSound = Bundle.main.url(forResource: resource, withExtension: "mp3") else { 
    // handle file not found here 
    return 
} 

// use alertSound here 
+0

仍然是同樣的問題...文件未找到... – user2971617

+0

audioselectionne來自prepareforsegue並聲明像這樣var audioselectionne:String? – user2971617

+0

我想這是同樣的問題在這裏... http://stackoverflow.com/questions/39537177/swift-3-incorrect-string-interpolation-with-implicitly-unwrapped-optionals – user2971617

相關問題