Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Filter string by using start with

Tags:

arrays

swift

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)

like image 533
Yen Avatar asked Dec 07 '25 04:12

Yen


2 Answers

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)
like image 82
Rakesha Shastri Avatar answered Dec 08 '25 18:12

Rakesha Shastri


You must use string.hasPrefix(string)

like image 36
Axbor Axrorov Avatar answered Dec 08 '25 19:12

Axbor Axrorov