How To Filter An Array In Swift

By Eddy Chung

Filtering an array is a common problem Swift developers face.

How To Filter An Array In Swift With Code Examples

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.

If you liked this post, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts