2016-01-24 38 views
0

我只是轉換我的應用程序斯威夫特2,當然,我得到一個錯誤信息:調用可以拋出錯誤消息,斯威夫特2

「呼叫可以拋出,但沒有打上‘嘗試’和eror是不是處理「

我在這裏搜索如何解決這個問題,但答案比錯誤本身更令我困惑。大聲笑。

我的應用程序完美工作,直到我將它改成斯威夫特2.精彩......

var myPlayer = AVAudioPlayer() 

var yourSound1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("RemSound_01", ofType: "wav")!) 
func initYourSound() { 
    myPlayer = AVAudioPlayer(contentsOfURL: yourSound1, fileTypeHint: nil) 
    myPlayer.prepareToPlay() 
    myPlayer.volume = 1.0 // < for setting initial volume, still not perfected. 
} 

在下面一行的錯誤拋出:

myPlayer = AVAudioPlayer(contentsOfURL:yourSound1,fileTypeHint:無)

我該如何解決這個問題?我明白Swift正在試圖「普遍化」錯誤處理,但是通過打破最簡單的代碼這樣做對我來說似乎很愚蠢。

謝謝你的幫助。

+0

使用Do-嘗試捕獲。一個簡單的例子在這裏:http://stackoverflow.com/a/34767908/2227743 – Moritz

+0

我會嘗試你的建議。謝謝。 –

+0

請注意,該方法的文檔現在說:「您可以在try語句中調用此方法,並處理do語句的catch子句中的任何錯誤,如Swift編程語言(Swift 2.1)中的錯誤處理中所述」。 –

回答

1

這是您正在尋找的模式。

<throwing function> // compiler error in Swift 2  
do { try <throwing function> } catch { } 

在抓住你通常會得到一個錯誤,你可以進一步處理。

0

這個作品在雨燕2.0,把它放在你的viewDidLoad方法...

do { 
     try AudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, fileTypeHint: nil) 
    } catch { 
     print("errorin do-try-catch") 
    } 

其中ButtonAudioURL

var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Besides", ofType: "mp3")!) 
+0

這就是我一直在尋找的。謝謝! –

+0

這是我如何改良我的代碼片段: FUNC initYourSound(){ 做{ 嘗試myPlayer = AVAudioPlayer(contentsOfURL:shotgunSound,fileTypeHint:無) myPlayer.prepareToPlay() myPlayer.volume = 1.0 // <爲了設定初始音量,還沒有完善。 } catch { //處理錯誤 } –

+0

我能夠編譯,但現在我得到這個錯誤:SIGABRT。我的AppDelegate swift文件的第1行: 2016-01-25 08:51:52.395 WarningShot1.0.0 [277:13379] - [WarningShot1_0_0.ViewController playMySound:]:無法識別的選擇器發送到實例0x154e4f7c0 2016-01-25 08:51:52.397 WarningShot1.0.0 [277:13379] ***由於未捕獲異常'NSInvalidArgumentException',原因:' - [WarningShot1_0_0.ViewController playMySound:]:發送到實例0x154e4f7c0的無法識別的選擇器' libC++ ABI。dylib:以NSException類型的未捕獲異常終止 –