Published Nov 14, 2022
Contribute to Docs

The .subtracting() method creates a new set containing the elements from the target set that are not in the given set.


newSet = targetSet.subtracting(givenSet)

The elements of givenSet are removed from the elements of targetSet and what elements remain are placed into newSet.


In the example below, the elements from the fruit set are removed from the elements in the produce set and the remaining elements are placed in the new veggies set:

let produce: Set = ["Lettuce", "Apples", "Carrots", "Bananas", "Broccoli", "Onions"]
let fruit: Set = ["Apples", "Bananas"]
let veggies = produce.subtracting(fruit)

This will output:

["Lettuce", "Carrots", "Broccoli", "Onions"]

Note: A set is an unordered data structure, so output elements may be ordered differently.

All contributors

Looking to contribute?

Learn Swift on Codecademy