【问题标题】:how use swift await func in onSubmit block如何在 onSubmit 块中使用 swift await 函数
【发布时间】:2021-12-25 22:29:48
【问题描述】:

我有一个包含搜索数据的列表。 获取我想调用的数据以等待 func (swift 5.5) 但我收到此错误:

"不能将'() async -> ()' 类型的函数传递给期望的参数 同步函数类型"

这是我的代码:

struct ContentView: View {


@ObservedObject var twitterAPI: TwitterAPI = TwitterAPI()

@State private var searchText = "TheEllenShow" // TheEllenShow

var body: some View {
    NavigationView {
        VStack{
            if twitterAPI.twitterSearchResults?.resultDataVM != nil{
                List {
                    ForEach((twitterAPI.twitterSearchResults?.resultDataVM)!) { item in
                        Text(item.text)
                    }
                }
                .refreshable {
                    await twitterAPI.executeQuery(userName: searchText)
                }
            }else{
                Text("Loading")
            }
            Spacer()
            
            
        }
        .searchable(text: $searchText)
        .onSubmit(of: .search) {
            await twitterAPI.executeQuery(userName: searchText)
        }

        .navigationTitle("Twitter")
        
    }
    .task {
        await twitterAPI.executeQuery(userName: searchText)
    }
}  }

【问题讨论】:

    标签: swift swiftui async-await synchronous swift5.5


    【解决方案1】:

    要从同步代码块调用异步代码,您可以创建Task 对象:

    .onSubmit(of: .search) {
      Task {
        await twitterAPI.executeQuery(userName: searchText)
      }
    }
    

    【讨论】:

    • 非常感谢!例外工作!你有可以深化的来源吗?
    • @isreal_b_2012 查找有关并发的 WWDC 2021 视频。除此之外,来自 raywenderlich.com 的 Modern Concurrency in Swift 书真正深入探讨了 async/await 并发性及其在现代应用程序中的应用。
    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2020-07-29
    • 2023-02-06
    • 2022-01-27
    • 2018-11-16
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多