What is the set.subtract() method in Swift?

Overview

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.

Syntax

set1.subtract(set1)
Subtracting a set from another set syntax

Parameters

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.

Return value

The value returned is set1 with some elements removed.

Code example

// create some sets
var 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 elements
names.subtract(workers)
numbers.subtract(evenNumbers)
// print current values of sets
print(names)
print(numbers)

Explanation

  • Lines 2–5: We create some sets and initialize them.
  • Line 8 and 9: We use the subtract() method to remove or subtract some elements.
  • Line 12 and 13: Because the subtract() method removed some elements from the sets, we print these sets to see the difference from the original sets.

Free Resources