How do I implement search and filtering in Combine with Swift?

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) } } } }

Swift Combine Search Filtering SwiftUI Reactive Programming