Reputation: 13514
I have an array of countries. I need to search and update array with searched text but starting with initial char match not anywhere in the string.
For eg: If I search in it should return India, Indonesia... not ChINa...
I have created bleow method which looks into whole string rather then initial char.
Also, I don't have any range in this function so how can I get range from string?
func searchCountry(for string: String) {
if !string.isEmpty {
let filtered = countries?.filter {
$0.name?.range(of: string,
options: .caseInsensitive) != nil
}
guard let filteredCountries = filtered else { return }
}
}
Upvotes: 0
Views: 83
Reputation: 707
You can also use this for appropriate output
func searchCountry(for string: String?) {
if let searchText = string {
let filter = countries.filter({ $0.lowercased().hasPrefix(searchText.lowercased()) })
print(filter)
}
}
Upvotes: 3
Reputation: 931
$0.name?.range(of: string,options: [.anchored, .caseInsensitive]) != nil
Use anchored to search the initials. It starts from the start.
Upvotes: 2