考虑以下(愚蠢的)例子:
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()))
}
任务中的所有三行似乎都可以工作。它们是相等的吗,还是有我应该注意的陷阱?谢谢。
像try
一样,Swift允许你将await
关键字放在包含async
方法的表达式的任何部分:
func ƒ<T>(_ v: T) -> T { v }
// All equivalent:
func somethingThatThrows() throws {}
print(ƒ(try somethingThatThrows()))
print(try ƒ(somethingThatThrows()))
try print(ƒ(somethingThatThrows()))
// All equivalent:
func someAsyncFunc() async {}
Task {
print(ƒ(await someAsyncFunc()))
print(await ƒ(someAsyncFunc()))
await print(ƒ(someAsyncFunc()))
}
迅速语法参考await
关键字也有一个例子,放置await
很重要(await
ing只有整个表达式的子表达式需要await
ed),但它不是完全相关:
// await applies to both function calls
sum = await someAsyncFunction() + anotherAsyncFunction()
// await applies to both function calls
sum = await (someAsyncFunction() + anotherAsyncFunction())
// Error: await applies only to the first function call
sum = (await someAsyncFunction()) + anotherAsyncFunction()