2015-11-06 72 views
0

這是一個簡單的雨燕2.0的問題,希望能有一個簡單的答案:爲什麼在設置AVAudioSession類別時不能使用警衛?

爲什麼下面的代碼給出一個錯誤「不明確提及成員setCategory」:

guard AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) else { 
    // 
} 

然而,這個代碼不拋出錯誤:

do { 
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) 
} catch { 
    // 
} 

我不打算採取任何行動,如果這一呼籲並沒有失敗,但我還是不喜歡使用try! - 所以我可以guard這種說法?或者,我誤解了guard

回答

2

Control Flow文檔:

Early exit
A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed.

一個典型的例子是

guard <someCondition> else { return } 

「提前歸還」 從如果條件不滿足的功能。

但扔功能都沒有布爾表達式, 他們必須被一些「嘗試情境」之稱,在 Error Handling記載:

Handling Errors
When a function throws an error, it changes the flow of your program, so it’s important that you can quickly identify places in your code that can throw errors. To identify these places in your code, write the try keyword—or the try? or try! variation—before a piece of code that calls a function, method, or initializer that can throw an error.

所以這是完全不同的事情。 guard陳述 不能與投擲功能一起使用。

如果你不關心成功或投擲功能衰竭, 使用try?而忽略結果作爲 An elegant way to ignore any errors thrown by a method。在你的情況下:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) 
+0

完美 - 謝謝你! – Luke

相關問題