To filter a list or an array in Swift, we will use the filter
method, which creates a new array containing only the elements of the original array that meet the criteria defined in a closure.
Here's an example:
main.swift152 chars6 lines
In the above example, we have an array of numbers
. We want to filter out only the even numbers from the array. So, we use the filter
method on numbers
, and pass a closure as an argument to the method that returns true
for even numbers. The closure { $0 % 2 == 0 }
takes each element of the array and checks if it's divisible by 2. If it is, it returns true
, which means that the element should be included in the filtered array.
Note that the filter
method returns a new array with the filtered elements, without modifying the original array.
gistlibby LogSnag