Swift Set subtract()

The subtract() method returns the set difference between two sets.

Example

var A: Set = ["a", "b", "c", "d"]
var B: Set = ["c", "f", "g"]

// equivalent to A-B A.subtract(B)
print("A-B =",A) // Output: A-B = ["d", "b", "a"]

subtract() Syntax

The syntax of the set subtract() method is:

set.subtract(otherSet)

Here, set is an object of the Set class.


subtract() Parameters

The subtract() method takes a single parameter:

  • otherSet - The set of elements.

Note: The other must be a finite set.


subtract() Return Value

  • The subtract() method returns set after removing the common elements of set and otherSet.

Example 1: Swift Set subtract()

var A: Set = [1,2,3,4]
var B: Set = [2,3,6,8]
var C: Set = [5,6,7,8]

// compute A-B A.subtract(B)
print("A-B=", A)
// compute B-C B.subtract(C)
print("B-C=", B)

Output

A-B= [4, 1]
B-C= [3, 2]

Here, we have used the subtract() method to compute the subtraction between A and B & B and C respectively.


Example 2: Use of Swift subtract() and Ranges

// create a set that ranges from 1 to 4
var total = Set(1...4)

// compute subtraction total.subtract([2,5,6])
print(total)

Output

[3, 1, 4]

Here, 1...14 represents a set of numbers that ranges from 1 to 4 and is assigned to total.

Finally, we have computed the subtraction between total and [2,5,6].

Did you find this article helpful?