Paco89
Paco89

Reputation: 25

Search Array with depending order

I got a question regarding filtering an array.

Let's assume I got an array of country names:

let countries = [Albania, Bahrain, Barbados, Denmark, France, Zimbabwe]

now I want to filter this array to check if it contains a certain String let say "ba". I can do this easily with

countries = countries.filter{ $0.contains("ba")}

which returns

Albania, Bahrain, Barbados, Zimbabwe

But I actually want the order of letters to matter. Therefore, the result "Albania" and "Zimbabwe" should not appear and only "Bahrain" and "Barbados" as their name starts with an Ba.

Is there any way to do this to avoid a huge for loop going through all entites checking individually for each character?

Upvotes: 1

Views: 106

Answers (2)

Abizern
Abizern

Reputation: 150615

You can take care of the case and the filtering in one step:

let countries = ["Albania", "Bahrain", "Barbados", "Denmark", "France", "Zimbabwe"]

let filtered = countries.filter { $0.lowercased().hasPrefix("ba") } // -> ["Bahrain", "Barbados"]

This lowercases the country names before applying the filter's test, but doesn't change the original array, so the results have the same case.

This is important because you might incorrectly want to do this in two steps for readability:

countries
    .map { $0.lowercased()}
    .filter { $0.hasPrefix("ba")}

But this returns ["bahrain", "barbados"] because the filter is being applied to the now lowercased array.

Upvotes: 0

Tom E
Tom E

Reputation: 1607

Use .hasPrefix instead of .contains, like this:

print(countries.filter{ $0.hasPrefix("Ba") })

Note that this is case sensitive. BTW, in your example, the problem was not missing order of letters but the fact that .contains respects case as do most methods in swift.

Upvotes: 3

Related Questions