Swift Array – Filter Elements based on Condition
To filter elements of a Swift Array, call filter() method on this array and pass the predicate/condition to the filter() method.
filter() method returns a new array with the elements of the original array, that satisfy the given condition.
Only those elements that satisfy the given condition, or return true for the given condition, will make it to the resulting array.
Example
In the following program, we will take an array of numbers, and filter only those numbers that are greater than 10.
main.swift
</>
Copy
var arr = [1, 99, 6, 74, 5]
let result = arr.filter { $0 > 10 }
print("Original Array : \(arr)")
print("Filtered Array : \(result)")
Output
Conclusion
Concluding this Swift Tutorial, we learned how to filter a given array based on a specific condition.