What is the subtracting(_:) method of a set in Swift?

Overview

The subtracting(_:) method of a set in Swift creates a new set with elements of a particular set that do not occur in a given set. We can use it between sets, or between a set and a sequence like an array.

Syntax

set.subtracting(sequence)
Syntax for subtracting(_:) method in Swift

Parameters

sequence: This could be another set, or a sequence such as an array.

Return value

This method returns a new set that contains elements of the set set that are not in the sequence sequence.

Code example

// Create some sets
let evenNumbers : Set = [10, 2, 6, 8, 4]
let oddNumbers : Set = [11, 5, 7, 3, 9]
let first_names : Set = ["john", "jane", "henry", "mark"]
// Create some array sequences
let primeNumbers = [2, 3, 5, 7, 11]
let last_names = ["doe", "muller", "mark", "henry"]
// Perform the subtracting
print(evenNumbers.subtracting(primeNumbers))
print(oddNumbers.subtracting(primeNumbers))
print(first_names.subtracting(last_names))

Explanation

  • Lines 2–4: We create and initialize some set variables.
  • Lines 7–8: We create some sequences.
  • Lines 11–13: We invoke the subtracting(_:) method on the sets and pass along the arrays as arguments. Then, we print the results to the console.