为什么设置AVAudioSession类别时不能使用guard?

Why can’t I use guard when setting AVAudioSession category?

这是一个简单的 Swift 2.0 问题,希望有一个简单的答案:

为什么下面的代码报错“Ambiguous reference to member setCategory”:

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

然而这段代码并没有抛出那个错误:

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

如果这个调用没有失败,我不打算采取任何行动,但我仍然不想使用 try! – 那么我可以 guard 这个声明吗?或者,我是不是误会了guard

来自 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 }
如果不满足条件,则从函数

到 "early return"。

但是抛出函数不是布尔表达式, 它们 必须 在某些 "try context" 中被调用,如 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? 并忽略结果,如 。在你的情况下:

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