Sets in Swift: Creating, Manipulating, and Iterating Over Collections

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

by The Captain

April 23, 2024
Working with Sets in Swift

Working with Sets in Swift

Sets in Swift are unordered collections of unique elements. They are a great way to store and manage distinct values without any duplicates. In this tutorial, we will explore how to work with sets in Swift and perform common operations using code snippets.

Creating a Set

To create a set in Swift, you can use the following syntax:

var fruits: Set = ["apple", "banana", "orange"]}

Adding and Removing Elements

You can add elements to a set using the `insert` method:


To remove an element from a set, you can use the `remove` method:


Checking for Element Existence

You can check if a set contains a specific element using the `contains` method:

if fruits.contains("apple") {
    print("Apple is in the set")

Set Operations

Sets support various operations such as union, intersection, and subtraction. Here's an example of performing a union operation between two sets:

let moreFruits: Set = ["kiwi", "pineapple"]
let allFruits = fruits.union(moreFruits)}

Iterating Over a Set

You can iterate over the elements of a set using a `for-in` loop:

for fruit in fruits {


Sets are a powerful data structure in Swift that allows you to store unique values efficiently. By understanding how to create sets, add and remove elements, check for element existence, perform set operations, and iterate over sets, you can leverage sets in your Swift projects effectively.