'SwiftUI: search for lower and upper case letters [duplicate]
I'm following this tutorial on adding a search bar in SwiftUI.
It doesn't work if i search by only typing with lower case letters when a name starts with higher case letters and vice versa. This is for a macOS app.
import SwiftUI
struct ContentView: View {
let names = ["Holly", "Josh", "Rhonda", "Ted"]
@State private var searchText = ""
var body: some View {
ScrollView {
VStack(spacing: 20) {
ForEach(searchResults, id: \.self) { name in
Text(name)
.foregroundColor(.white)
.font(.largeTitle)
.frame(width: 330, height: 100)
.background(Color.red)
}
.searchable(text: $searchText)
}
}
.frame(width: 350,height: 350)
}
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.contains(searchText) }
}
}
}
Solution 1:[1]
There is a dedicated API
return names.filter { $0.localizedCaseInsensitiveContains(searchText) }
Solution 2:[2]
If you would like to ignore case, you could convert the search criteria and the content you're searching to lowercase in this line
return names.filter { $0.contains(searchText) }
You could use the .lowercased() method.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vadian |
| Solution 2 | Fredrik A. |

