filter a list in swift

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.swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let filteredNumbers = numbers.filter { $0 % 2 == 0 }

print(filteredNumbers) // Output: [2, 4, 6, 8, 10]
152 chars
6 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