与try
类似,Swift允许您在包含async
方法的表达式的任何部分放置await
关键字:
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()))
}
Swift grammar reference for the await
keyword确实有一个例子,说明await
的位置很重要(await
只对需要await
ed的整个表达式的子表达式进行await
ing),但在这里并不太相关:
// 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()