Filtering an array is a common problem Swift developers face.
Let’s say you want to filter an array and only keep elements that are prefixed with “test”.
Here’s our string array example:
let strArrayExample = ["test-1", "hello", "test-2", "blah blah", "test-3"]
To get an array with only elements that are prefixed with “test”, we write the following code:
let prefixedWithTest = strArrayExample.filter { $0.hasPrefix("test") }
Printing out prefixedWithTest
will have the following output:
["test-1", "test-2", "test-3"]
You can also do the same with numbers. Here’s an example:
let numbersArray = [-5, -2, -3, 1, 5, 100]
Say we want to filter for only negative numbers:
let negative = numbersArray.filter { $0 < 0 }
print(negative)
This will result in the following printed:
[-5, -2, -3]
You can make the condition to filter on anything. Here’s an example where we want only even numbers:
let even = numbersArray.filter { $0 % 2 == 0 }
print(even)
Results in:
[-2, 100]
That’s how you filter arrays.
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.