gpt4 book ai didi

swift - "try"关键字的位置差异

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:43 25 4
gpt4 key购买 nike

我有一个音频播放器的全局变量。try word放在变量初始化之前有什么区别

do{
try audioPlayer = AVAudioPlayer(contentsOf: audioURL)
}catch {}

在调用构造函数之前放置try

do{
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
}catch {}

当然上面两种情况没有任何编译错误。谢谢

最佳答案

没有实际区别。作为said by the language guide (强调我的):

When the expression on the left hand side of a binary operator is marked with try, try?, or try!, that operator applies to the whole binary expression. That said, you can use parentheses to be explicit about the scope of the operator’s application.

// try applies to both function calls
sum = try someThrowingFunction() + anotherThrowingFunction()

// try applies to both function calls
sum = try (someThrowingFunction() + anotherThrowingFunction())

// Error: try applies only to the first function call
sum = (try someThrowingFunction()) + anotherThrowingFunction()

就像+ , 赋值也是一个二元运算符。因此,当你说

do{
try audioPlayer = AVAudioPlayer(contentsOf: audioURL)
}catch {}

try适用于两个 表达式 audioPlayerAVAudioPlayer(contentsOf: audioURL) .孤独的表情audioPlayer 不可能在这里抛出错误——因此 try在这种情况下仅适用于对 AVAudioPlayer 的调用的 init(contentsOf:)可以抛出。

推导of the grammar这是:

//           "try"          "audioPlayer"     "= AVAudioPlayer(contentsOf: audioURL)"
expression → <b>try-operator<sub>­opt</sub> ­prefix-expression ­binary-expressions­<sub>opt</sub></b>

prefix-expression → prefix-operator­<sub>opt</sub> ­postfix-expression
postfix-expression → primary-expression­
primary-expression → identifier­ generic-argument-clause<sub>­opt</sub>
identifier­ → // matches "audioPlayer" (I'm not going to fully derive this bit further)

binary-expressions → binary-expression ­binary-expressions<sub>­opt</sub>
binary-expression → <b>assignment-operator</b> ­try-operator­<sub>opt­</sub> prefix-expression
prefix-expression → prefix-operator­<sub>opt</sub> postfix-expression
postfix-expression → initializer-expression­ // matches AVAudioPlayer(contentsOf: audioURL)

当你说

do{
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
}catch {}

您使用的事实是赋值表达式 has the grammar of :

binary-expression → assignment-operator <b>­try-operator<sub>­opt</sub></b> ­prefix-expression­

如您所见,try-operator 可以出现在此处运算符的右侧,因此将应用于 prefix-expression – 在这种情况下是 AVAudioPlayer.init(contentsOf:) .

所以在这两种情况下,您都捕获了可能从 AVAudioPlayer.init(contentsOf:) 抛出的错误.第一个示例仅包含从运算符左侧的表达式中抛出错误的可能性,它不可能这样做。

使用你觉得更舒服的那个——我个人的喜好,以及与try的位置更一致的选项。在语言的其他地方,就是把try在右侧。

关于swift - "try"关键字的位置差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42693946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com