“尝试”关键字的位置差异

2023-11-30

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

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

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

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

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


没有实际区别。作为语言指南说的(强调我的):

当二元运算符左边的表达式为 标有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-operator­opt ­prefix-expression ­binary-expressions­opt

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

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

当你说

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

您正在使用赋值表达式这一事实语法为:

binary-expression → assignment-operator ­try-operator­opt ­prefix-expression­

如您所见,try-operator can also出现在此处运算符的右侧,因此将适用于prefix-expression– 在本例中是AVAudioPlayer.init(contentsOf:).

因此,在这两种情况下,您都会捕获可能引发的错误AVAudioPlayer.init(contentsOf:)。第一个示例仅包括从运算符左侧的表达式抛出错误的可能性,它是不可能 do.

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“尝试”关键字的位置差异 的相关文章

随机推荐