Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Set Methods in Swift
Written by Team Kodeco

Sets in Swift are unordered collections of unique elements. They are useful for storing and manipulating sets of data, such as a list of unique words in a document or a set of unique integers.

Swift provides a variety of methods for manipulating and querying sets. Here are some examples:

// create a set of integers
var primes: Set = [2, 3, 5, 7, 11, 13]

// add an element to the set
primes.insert(17)

// remove an element from the set
primes.remove(5)

// check if set contains an element
let isPrime = primes.contains(11)
print(isPrime) // true

// get the number of elements in a set
let count = primes.count
print(count) // 6

// check if set is empty
let isEmpty = primes.isEmpty
print(isEmpty) // false

// loop through all elements in a set
for prime in primes {
  print(prime)
}

You can also use set methods to perform common set operations such as union, intersection, and symmetric difference. For example, the following code demonstrates how to create two sets and find their union:

let oddNumbers: Set = [1, 3, 5, 7, 9]
let evenNumbers: Set = [2, 4, 6, 8, 10]

let allNumbers = oddNumbers.union(evenNumbers)
print(allNumbers) // [2, 5, 6, 9, 4, 10, 3, 7, 1, 8]

You can also use the intersection(_:) and symmetricDifference(_:) methods to find the intersection and symmetric difference of two sets, respectively.

Keep in mind that if you want to change the original set instead of creating a new one you can use the formUnion(_:), formIntersection(_:) and formSymmetricDifference(_:) methods.

© 2024 Kodeco Inc.