Reputation: 45
I have an array as follows:
let array = ["sam", "andrew", "character"]
And I want to get every element in the array that starts with a character I type
My problem is when i type "a" the output is "sam", "andrew", and "character".
I want to get the output to only be "andrew". (The string must start from left to right when searching)
Upvotes: 2
Views: 3273
Reputation: 1014
You can try to use this in Swift 5:
let filteredNames = names.filter{$0.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil}
Upvotes: 0
Reputation: 11243
You need to filter your array using hasPrefix
var names = ["sam", "andrew", "character"]
var searchString = "a"
let filteredNames = names.filter({ $0.hasPrefix(searchString) })
print(filteredNames)
Upvotes: 6