对于我的应用程序,我正在创建一个搜索视图。搜索可以在多个范围内完成,可用范围是动态的。加载搜索视图时,将使用 API 调用获取范围,但为此,所选范围是可选的。哪些范围可用是未知的,因此在获取完成之前没有选定的范围(默认情况下选择第一个范围)。拥有可选的选定范围是行不通的,当我通过硬编码一个值使其成为非可选时,它确实可以工作。有没有办法让
.searchSopes
使用可选选择,或者有没有办法在加载搜索范围时让选择不可选?
struct SearchView: View {
@State private var searchText = ""
@State private var searchScopes = [SearchScope]()
@State private var searchScope: SearchScope?
var body: some View {
NavigationStack {
Text("Searching for \(searchText)")
}
.searchable(text: $searchText)
.searchScopes($searchScope, activation: .onSearchPresentation, {
ForEach(searchScopes) { scope in
Text(scope.label).tag(scope)
}
})
.task {
self.searchScopes = await httpClient.fetchSearchScopes()
if !searchScopes.isEmpty {
self.searchScope = searchScopes[0]
}
}
}
}
@Sweeper 是正确的,我犯了一个(常见的)错误,将非可选参数传递给
.tag()
方法,而所选的搜索范围是可选的。通过将 .tag()
方法中的搜索范围转换为 this answer 中建议的可选范围。
ForEach(searchScopes) { scope in
Text(scope.label).tag(scope as SearchScope?)
}