没有实际区别。作为语言指南说的(强调我的):
当二元运算符左边的表达式为
标有try
, try?
, or try!
,该运算符适用于
整个二进制表达式。也就是说,您可以使用括号
明确运营商的应用范围。
// 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 {}
The try
适用于both表达式audioPlayer
and AVAudioPlayer(contentsOf: audioURL)
。孤独的表情audioPlayer
不可能在这里抛出一个错误 - 因此try
在这种情况下仅适用于调用AVAudioPlayer
's init(contentsOf:)
, which can throw.
推导语法的因为这是:
// "try" "audioPlayer" "= AVAudioPlayer(contentsOf: audioURL)"
expression → try-operatoropt prefix-expression binary-expressionsopt
prefix-expression → prefix-operatoropt postfix-expression
postfix-expression → primary-expression
primary-expression → identifier generic-argument-clauseopt
identifier → // matches "audioPlayer" (I'm not going to fully derive this bit further)
binary-expressions → binary-expression binary-expressionsopt
binary-expression → assignment-operator try-operatoropt prefix-expression
prefix-expression → prefix-operatoropt postfix-expression
postfix-expression → initializer-expression // matches AVAudioPlayer(contentsOf: audioURL)
当你说
do{
audioPlayer = try AVAudioPlayer(contentsOf: audioURL)
}catch {}
您正在使用赋值表达式这一事实语法为:
binary-expression → assignment-operator try-operatoropt prefix-expression
如您所见,try-operator
can also出现在此处运算符的右侧,因此将适用于prefix-expression
– 在本例中是AVAudioPlayer.init(contentsOf:)
.
因此,在这两种情况下,您都会捕获可能引发的错误AVAudioPlayer.init(contentsOf:)
。第一个示例仅包括从运算符左侧的表达式抛出错误的可能性,它是不可能 do.
使用你觉得更舒服的那个——我个人的喜好,以及与放置更一致的选项try
在语言的其他地方,就是把try
在右手侧。