Skip to content

Swift Sets

This tutorial belongs to the Swift series

Sets are used to create collections of non-repeated items.

While an array can contain many times the same item, you only have unique items in a set.

You can declare a set of Int values in this way:

let set: Set<Int> = [1, 2, 3]

or you can initialize it from an array:

let set = Set([1, 2, 3])

Add items to the set using insert():

var set = Set([1, 2, 3])
set.insert(17)

Unlike arrays, there is no order or position in a set. Items are retrieved and inserted randomly.

The way to print the content of a set ordered is to transform it into an array using the sorted() method:

var set = Set([2, 1, 3])
let orderedList = set.sorted()

To check if a set contains an element, use the contains() method:

var set = Set([1, 2, 3])
set.contains(2) //true

To get the number of items in the set, use the count property:

let set = Set([1, 2, 3])
set.count //3

If a set is empty, its isEmpty property is true.

let set = Set([1, 2, 3])
set.isEmpty //false

To remove one item from the array, use remove() passing the value of the element:

var set = Set([1, 2, 3])
set.remove(1)
//set is [2, 3]

To remove all items from the set, you can use removeAll():

set.removeAll()

Sets, like arrays, are passed by value, which means if you pass it to a function, or return it from a function, the set is copied.

Sets are great to perform set math operations like intersection, union, subtracting, and more.

These methods help with this:

Sets are collections, and they can be iterated over in loops.


→ Get my Swift Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list