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

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about swift: