【发布时间】:2021-07-26 05:24:26
【问题描述】:
我一直在测试 Swift 5.5 版本中预览的 async/await 功能,但我无法从异步函数收集结果并使用 SwiftUI 显示它们。这是我的代码:
import SwiftUI
struct AsyncTestView: View {
@State var text: String?
// Async function
func asyncGetText() async -> String {
Thread.sleep(forTimeInterval: 10)
return "My text"
}
// Stores the result of async function
func fetchText() async {
let text = await asyncGetText()
DispatchQueue.main.async {
self.text = text
}
}
var body: some View {
Text(text ?? "Loading")
.onAppear(perform: fetchText)
}
}
这会导致以下错误:
在不支持并发的函数中调用'async'
将 'async' 添加到函数 'fetchText()' 以使其异步
将async 添加到fetchText() 函数会导致.onAppear() 函数出现以下错误:
从'() async -> ()' 类型的'async' 函数到'() -> Void' 类型的同步函数的转换无效
在this article 中,他们使用@asyncHandler 标签来注释fetchText 函数,但是这会导致警告:'@asyncHandler' has been removed from the language'。
【问题讨论】:
-
Xcode 12.5 是 Swift 5.4 那么我们到底在说什么?您是否安装了不同的工具链?
-
是的,我下载了 Swift 5.5 Development Snapshot 工具链
标签: swift async-await swiftui swift5