import SwiftUI
struct FruitListView: View {
@State private var searchText = ""
let fruits = ["Banana", "Apple", "Cherry", "Date", "Grape", "Kiwi"]
var filteredFruits: [String] {
fruits.filter { fruit in
searchText.isEmpty || fruit.localizedCaseInsensitiveContains(searchText)
}
.sorted()
}
var body: some View {
NavigationView {
VStack {
TextField("Search", text: $searchText)
.padding()
.textFieldStyle(RoundedBorderTextFieldStyle())
.accessibilityLabel("Search fruits")
List(filteredFruits, id: \.self) { fruit in
Text(fruit)
}
.listStyle(PlainListStyle())
}
.navigationTitle("Filtered Sorted List")
}
}
}
struct FruitListView_Previews: PreviewProvider {
static var previews: some View {
FruitListView()
}
}We created a computed property filteredFruits that filters the fruits array using the search text. It uses localizedCaseInsensitiveContains to check if the fruit name includes the search text, ignoring case. If the search text is empty, it shows all fruits. Then it sorts the filtered list alphabetically with sorted().
The List displays the filtered and sorted fruits. The TextField updates searchText as the user types, so the list updates in real-time.
We also added an accessibility label to the search field for better usability.