To remove items from a set based on a condition in Swift, you can use the removeAll(where:) method with a closure that defines the condition.
In this example,
numberSet
containing integer values 1
, 2
, 3
, 4
, and 5
.removeAll(where:)
method with a closure that checks for even numbers to remove them from the set.numberSet
to see the removed items.var numberSet: Set<Int> = [1, 2, 3, 4, 5]
numberSet.removeAll(where: { $0 % 2 == 0 })
print(numberSet)
[1, 3, 5]
In this example,
stringSet
containing string values "apple"
, "banana"
, "cherry"
, "date"
, and "grape"
.removeAll(where:)
method with a closure that checks for string length less than 6 characters to remove them from the set.stringSet
to see the removed items.var stringSet: Set<String> = ["apple", "banana", "cherry", "date", "grape"]
stringSet.removeAll(where: { $0.count < 6 })
print(stringSet)
["banana", "cherry"]
In this tutorial, we learned How to Remove Items from Set based on a Condition in Swift language with well detailed examples.