In Swift, a set is a collection of unique values that can be compared for equality. Subtracting 2 sets is the operation of removing the elements of one set that are also present in another set. Let’s say you have set A and set B. Then, subtracting set B from set A means removing the elements of set B that are also in set A.
The Swift programming language provides 2 built-in methods that can make our lives much easier when subtracting 2 sets. They are subtracting()
and subtract()
.
subtracting()
The syntax:
newSet = targetSet.subtracting(givenSet)
The elements of givenSet
are removed from the elements of targetSet
and what elements remain are placed into newSet
.
Example:
// a set of numbers
let numbers: Set = [1, 2, 3, 4, 5]
// a set that contains only odd numbers
let odds: Set = [1, 3, 5]
// subtract the odd numbers from the numbers
let evens = numbers.subtracting(odds)
print(evens)
Output:
[2, 4]
Another example:
// a set of letters
let letters: Set = ["a", "b", "c", "d", "e"]
// a set of vowels
let vowels: [String] = ["a", "e", "i", "o", "u"]
// subtract vowels from letters to get consonants
let consonants = letters.subtracting(vowels)
print(consonants)
Output:
["b", "d", "c"]
subtract()
The subtract()
method works similarly to the subtracting()
method, but it modifies the original set instead of creating a new one1. The syntax of the subtract()
method is:
targetSet.subtract(givenSet)
The elements of givenSet
are removed from the elements of targetSet
. The result is that targetSet
is changed to contain only the elements that are not in givenSet
.
Example:
// all items
var allItems:Set<String> = ["Item 1", "Item 2", "Item 3", "Item 4"]
// bad items
let badItems:Set<String> = ["Item 1", "Item 2"]
// remove bad items
allItems.subtract(badItems)
print(allItems)
Output:
["Item 3", "Item 4"]
Note that when using the subtract()
method, your target set must be mutable (declared with the var
keyword instead of the let
keyword).
That’s it. Happy coding & have a nice day!