How to filter an Array in Swift

To filter an array in Swift use the Array.filter method.

let strings = ["The", "lazy", "red", "fox", "was", "fast"]

let filteredArray = strings.filter {
    $0.count >= 4
}
// Output:
// filteredArray will return ["lazy", "fast"]

When you have an Array of elements and 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:

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.

Previous
Previous

Topics to learn before entering a role as a Senior Developer