WWDC21介绍雨燕5.5, with 异步/等待。继探索 Swift 中的结构化并发 https://developer.apple.com/wwdc21/10134 and 在 Swift 中认识 async/await https://developer.apple.com/wwdc21/10132WWDC21 会议,我正在尝试使用异步让功能。
这是我的游乐场代码:
func doIt() async -> String {
let t = TimeInterval.random(in: 0.25 ... 2.0)
Thread.sleep(forTimeInterval: t)
return String("\(Double.random(in: 0...1000))")
}
async {
async let a = doIt()
async let b = doIt()
async let c = doIt()
async let d = doIt()
let results = await [a, b, c, d]
for result in results {
print(" \(result)")
}
}
但是,对于每个“async let”行,我收到此错误:
error: AsyncLetSwift55WWDC21.playground:12:15: error: expression is 'async' but is not marked with 'await'
async let a = doIt()
^
await
Paul Hudson's blog showed this example:
The Exploring structured currency video has this example at about the 8:10 mark:
编辑:这似乎确实是游乐场特定的问题。根据关于同一问题的建议苹果开发者论坛 https://developer.apple.com/forums/thread/682344,运行相同的代码(好的,我添加了sleep(10)
对于 macOS,在异步块之后到源文件的末尾,因此应用程序不会在异步调用完成之前终止)作为 macOS 命令行项目不会给出任何错误并产生正确的输出。
这是一个错误,还是我只是不理解某些事情?