The subtract()
method of the Set
class is used to remove elements of a given set present in another. This means that if a particular set has elements that are present in another, we can call the subtract()
method. These elements will be removed from this particular set.
set1.subtract(set1)
set1
: This is the set from which we want to remove some elements present in another set set2
.
set2
: This is the second set whose elements that are found in set1
will be removed in set1
.
The value returned is set1
with some elements removed.
// create some setsvar names: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]var workers: Set = ["Alicia", "Bethany", "Diana"]var numbers: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]var evenNumbers: Set = [2, 4, 6, 8, 10]// call the subtract method to remove some elementsnames.subtract(workers)numbers.subtract(evenNumbers)// print current values of setsprint(names)print(numbers)
subtract()
method to remove or subtract some elements.subtract()
method removed some elements from the sets, we print these sets to see the difference from the original sets.