Implementing search and filtering using Combine in Swift is a powerful way to handle dynamic data queries. Below is an example of how you can achieve this functionality.
import SwiftUI
import Combine
struct Item: Identifiable {
let id: UUID
let name: String
}
class ViewModel: ObservableObject {
@Published var items: [Item] = [
Item(id: UUID(), name: "Apple"),
Item(id: UUID(), name: "Banana"),
Item(id: UUID(), name: "Cherry")
]
@Published var searchText: String = ""
var cancellables = Set()
init() {
$searchText
.combineLatest($items)
.map { searchText, items in
return items.filter { item in
searchText.isEmpty || item.name.lowercased().contains(searchText.lowercased())
}
}
.assign(to: &$filteredItems)
}
@Published var filteredItems: [Item] = []
}
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()
var body: some View {
VStack {
TextField("Search items...", text: $viewModel.searchText)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
List(viewModel.filteredItems) { item in
Text(item.name)
}
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?