To filter elements of an array based on a condition in Swift, you can use the filter method.
In this example,
numbers
containing integers.filter
method with a closure to filter out even numbers.let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print("Even Numbers:", evenNumbers)
Even Numbers: [2, 4, 6, 8, 10]
In this example,
words
containing strings.filter
method with a closure to filter strings by their length.let words = ["apple", "banana", "cherry", "date", "fig"]
let filteredWords = words.filter { $0.count > 5 }
print("Filtered Words:", filteredWords)
Filtered Words: ["banana", "cherry"]
In this tutorial, we learned How to Filter Elements of an Array based on a Condition in Swift language with well detailed examples.