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
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
var set = Set([2, 1, 3]) let orderedList = set.sorted()
To check if a set contains an element, use the
var set = Set([1, 2, 3]) set.contains(2) //true
To get the number of items in the set, use the
let set = Set([1, 2, 3]) set.count //3
If a set is empty, its
isEmpty property is
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():
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.
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
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