在Swift 5.5中组成同步和异步功能
考虑以下(愚蠢的)示例:
func u () async -> UInt32 {
let r = UInt32(Int.random(in: 1...10))
sleep(r)
return r
}
func v(_ x: UInt32) -> UInt32 {
x
}
Task.init{
print(v(await u()))
print(await v(u()))
await print(v(u()))
}
任务中的所有三行似乎都起作用。它们是等效的,还是我应该知道任何陷阱?谢谢。
Consider the following (silly) example:
func u () async -> UInt32 {
let r = UInt32(Int.random(in: 1...10))
sleep(r)
return r
}
func v(_ x: UInt32) -> UInt32 {
x
}
Task.init{
print(v(await u()))
print(await v(u()))
await print(v(u()))
}
All three lines in the task appear to work. Are they equivalent, or are there any pitfalls I should be aware of? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
喜欢
尝试
,Swift允许您将等待
关键字放在表达式的任何部分,其中包含async
方法:Like
try
, Swift allows you to place theawait
keyword on any part of an expression that contains anasync
method:The Swift grammar reference for the
await
keyword does have an example for where placement ofawait
does matter (await
ing only a subexpression of a whole expression that needs to beawait
ed), but it's not quite relevant here: