小编Kay*_*try的帖子

如何在 Swift 5.5 中将 async/await 与 SwiftUI 一起使用?

我一直在测试 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()' 以使其异步

添加asyncfetchText()函数然后会导致函数出现以下错误.onAppear() …

async-await swift swift5 swiftui

10
推荐指数
3
解决办法
2740
查看次数

标签 统计

async-await ×1

swift ×1

swift5 ×1

swiftui ×1