To filter items of a set based on a condition in Swift, you can use the filter method to apply a filtering predicate and create a new set from the filtered items.
In this example,
numberSet
using the Set
type, which contains integer values 1
, 5
, 10
, 15
, and 20
.filter
method on numberSet
to filter the numbers greater than 5 using a closure as the filtering condition.filteredSet
using the Set
initializer with the filtered items from the filter
method.filteredSet
and print each filtered item to the console.var numberSet: Set<Int> = [1, 5, 10, 15, 20]
let filteredSet = numberSet.filter { $0 > 5 }
for num in filteredSet {
print(num)
}
10 15 20
In this example,
stringSet
using the Set
type, which contains string values "apple"
, "banana"
, "cherry"
, "date"
, and "grape"
.filter
method on stringSet
to filter the strings containing the letter 'a' using a closure as the filtering condition.filteredStringSet
using the Set
initializer with the filtered items from the filter
method.filteredStringSet
and print each filtered string to the console.var stringSet: Set<String> = ["apple", "banana", "cherry", "date", "grape"]
let filteredStringSet = stringSet.filter { $0.contains("a") }
for str in filteredStringSet {
print(str)
}
apple banana grape
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Swift language with well detailed examples.