Working with Sets in Swift: A Guide

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 26, 2024
Working with Sets in Swift

Working with Sets in Swift

Sets in Swift allow you to store unique values of the same type in a collection. Sets do not have a specific order and do not allow duplicate values. They are a great way to check for membership, intersect, and perform other set operations efficiently.

Here is an example of how you can work with sets in Swift:

// Creating a Set
var fruits: Set = ["Apple", "Banana", "Orange"]

// Adding an element to a Set
fruits.insert("Grapes")

// Removing an element from a Set
fruits.remove("Banana")

// Checking for membership
if fruits.contains("Apple") {
    print("Apple is in the set")
}

// Iterating over a Set
for fruit in fruits {
    print(fruit)
}

// Performing set operations
let otherFruits: Set = ["Pineapple", "Mango"]
let allFruits = fruits.union(otherFruits)

print(allFruits)}

In the code snippet above, we first create a Set called 'fruits' containing three fruit names. We then insert a new element 'Grapes' into the set and remove 'Banana'. We check if 'Apple' is a member of the set and iterate over all elements in the set. Finally, we perform a union operation with another set 'otherFruits' to combine all fruits into a single set 'allFruits'.

Sets in Swift provide efficient methods for set operations such as checking for membership, adding and removing elements, and performing set operations like union and intersection. They are a valuable tool for managing unique collections of data in your Swift code.