.filter()
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.
Syntax
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.
Example
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")})print(result)
This will output:
["Ariel", "Aurora"]
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.