How to filter an Array in Swift?

Published on: January 9, 2020

When you have an Array of elements, and you want to drop all elements that don't match specific criteria from the Array, you're looking for Array's filter(isIncluded:) method. Let's say you have an array of words and you only want to keep the words that are longer than three characters:

let words = ["hello", "world", "this", "is", "a", "list", "of", "strings"]
let filtered = words.filter { word in
  return word.count >= 3
} // filtered is ["hello", "world", "this", "list", "strings"]

The filter(isIncluded:) method takes a closure that is executed for every element in the source Array. If you return true from this closure, the element will be included in a new, filtered Array. If you return false, the element is ignored and won't be included in the new Array. When you apply a filter on an Array, the original Array is not modified. Instead, filter(isIncluded:) creates a new Array with only the elements you want.

You can perform any kind of calculation, comparison or computation in the closure that you use, just keep in mind that the more work you in your closure, the slower your filter might become. Ideally, you should make sure that you do as little work as possible when filtering an Array.

If you have any questions about this tip, or if you have feedback for me, don't hesitate to send me a Tweet!

Subscribe to my newsletter