Swift .subtracting()

st3hall2349189021's avatar
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.

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

Syntax

newSet = targetSet.subtracting(givenSet)

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

Example

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)
print(veggies)

This will output:

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

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

All contributors

Contribute to Docs

Learn Swift on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours