Yen
Yen

Reputation: 45

Swift: Filter string by using start with

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

Answers (3)

Menaim
Menaim

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

Rakesha Shastri
Rakesha Shastri

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

Axbor Axrorov
Axbor Axrorov

Reputation: 2806

You must use string.hasPrefix(string)

Upvotes: 3

Related Questions