Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
subtracting
communitycreator

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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))
Using the subtracting(_) method on sets and arrays

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.

RELATED TAGS

swift
subtracting
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring