[英]how use swift await func in onSubmit block
I have a list with data from the search.我有一个包含搜索数据的列表。 to get data I want to call to await func (swift 5.5) but I get this error:
获取我想调用 await func (swift 5.5) 的数据,但出现此错误:
"Cannot pass function of type '() async -> ()' to parameter expecting synchronous function type"
“无法将类型为‘() async -> ()’的函数传递给需要同步函数类型的参数”
this is my code:这是我的代码:
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)
}
} }
To call asynchronous code from a synchronous code block, you can create a Task
object:要从同步代码块调用异步代码,您可以创建一个
Task
对象:
.onSubmit(of: .search) {
Task {
await twitterAPI.executeQuery(userName: searchText)
}
}
You could bounce it over to .task
like this:你可以像这样将它反弹到
.task
:
@State var submittedSearch = ""
@State var results = []
.onSubmit(of: .search) {
submittedSearch = searchText
}
.task(id: submittedSearch) {
if submittedSearch.isEmpty {
return
}
results = await twitterAPI.executeQuery(userName: submittedSearch)
}
Has the advantage it will be cancelled and restarted if the search changes and also when the underlying UIView disappears.优点是如果搜索更改以及底层 UIView 消失时它将被取消并重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.