Published Jun 28, 2023
Contribute to Docs

The .filter() method takes an array and returns a new array with only elements that meet the condition stated in the filter. If none of the elements meet the condition stated in the filter, the method returns nil. The original, existing array is not affected by this method.


arrayName.filter({$0 condition })

The .filter() method takes a single condition parameter. It is a closure that returns a boolean value indicating whether a given array element is a match.

In the example below, the .filter() method is used to search through the names array. All items that meet the condition of starting with A will be returned.


var names = ["Ariel", "Jamsin", "Cinderella", "Aurora", "Belle", "Mulan", "Tiana", "Moana"]
// Return all elements that start with an "A"
var result = names.filter( {$0.hasPrefix("A")})

This will output:

["Ariel", "Aurora"]

All contributors

Looking to contribute?

Learn Swift on Codecademy