我一直在测试 Swift 5.5 版本中预览的异步/等待功能,但我无法从异步函数收集结果并使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这会导致以下错误:
在不支持并发的函数中调用 'async'
将 'async' 添加到函数 'fetchText()' 以使其异步
添加async到fetchText()函数然后会导致函数出现以下错误.onAppear() …