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])

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 is [2, 3]

To remove all items from the set, you can use 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.

→ Download my free Swift Handbook!



You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about swift: