Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

subtracting
set
swift
communitycreator

How to use the subtracting() method of a set in Swift

Theodore Kelechukwu Onyejiaku

Overview

The subtracting() method of a set in Swift is used to return a new set containing elements that do not occur in another supplied set.

Syntax

?set1.subtracting(set2)
Syntax for the subtracting() method in Swift

Parameters

set1: This is the set from which we want to return a new set that contains elements that do not occur in the set set2.

Return value

A new set is returned.

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]

// using the subtracting method
let nonWorkers = names.subtracting(workers)
let nonEvenNumbers = numbers.subtracting(evenNumbers)

// print results
print(nonWorkers)
print(nonEvenNumbers)
Using the subtracting() method of a Set in Swift

Code explanation

  • Lines 2–5: We create some sets and initialize them.
  • Lines 8 and 9: We return any elements not present in any supplied set using the subtracting() method.
  • Lines 12 and 13: We print the results to the console.

RELATED TAGS

subtracting
set
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring