Silvia EspaΓ±a Gil
Posted on June 10, 2024
Hola Mundo!
Welcome to a new article in a series of Swift 101 notes π I created these notes while learning the language and decided to share them because, why not?
If you're new to Swift or interested in learning more about this language, I invite you to follow my series! π
Last week I shared a post with the first part of collections which was arrays. Initially, I thought I would cover collections in two parts, but who wants to read that much in one go π π½ββοΈ? So, this will be the second part of what will likely be four parts. Next week, I'll share and try to cover Tuples and Dictionaries.
So, let's get to it πͺβ!
As a quick refresher from last week's chapter, "Collections" are types that store multiple values. They arrange all those values in certain ways so we can access them in the future.
Think of it like a fruit basket with many fruits in it. Similarly, arrays in Swift store multiple values of the same type in an ordered list, like a line of apples, oranges, and bananas neatly arranged in your basket πβπβπβ
There are many types of Collections, like Arrays which we already discussed. Today I want to share about β¨βSetsβ¨β.
Sets
Sets, like arrays and other collections, allow us to store many elements of the same type in a variable. However, sets store the values without any particular order.
The main characteristics of sets are:
- Order: Sets do not have a defined order; they store values in the way that Swift thinks is most effective.
- Elements canβt repeat itself: On sets all element values must be unique. If thereβs a duplicated one it will be ignored.
swift
let colors = Set(["red", "green", "blue"])
print(colors)
// Output: ["red", "blue", "green"]
let colors2 = Set(["red", "green", "blue", "green"])
print(colors2)
// Output: ["green", "red", "blue"]
To declare an empty set you specify the type of elements it will hold using the Set keyword followed by the type in angle brackets:
var mySet = Set<Int>()
You can also declare a set with initial values. Swift will infer the type of the set based on the type of the initial values:
var mySet: Set = [1, 2, 3, 4, 5]
or, specifying the type explicitly:
var mySet: Set<Int> = [1, 2, 3, 4, 5]
π₯β Remember that Sets do not maintain the order of elements and that repeated elements will be ignored π₯
Sets managing: accessing values and methods
Accessing sets values
Since sets have no specific order, we must access their elements using loops or by using their methods and properties.
Iterations on sets
To iterate over a set, we can use the for-in
loop. This allows us to access each element in the set one by one.
let fellowshipMembers: Set = ["Frodo", "Aragorn", "Gandalf", "Legolas", "Gimli", "Merry", "Pippin", "Boromir"]
for member in fellowshipMembers {
print(member)
}
// Output: This will print all the members
π§ Remember that Sets do not maintain the order of elements π§
Set methods and properties
Swift also provides us with some methods and properties that we may use and that can be useful for different operations.
Let's see the most used:
.count
This property counts how many elements are inside our Set.
let letter: Set = ["w", "e", "f", "o", "x"]
print(letter.count)
// Output: 5
.insert()
This method allows us to add new elements to our Set.
var groceryList: Set = ["Onions", "Apples", "Pasta"]
groceryList.insert("Bread")
print(groceryList)
// Possible output: ["Pasta", "Onions", "Bread", "Apples"]
.remove()
Allows us to remove an element from the set
var groceryList: Set = ["Onions", "Apples", "Pasta"]
groceryList.remove("Pasta")
print(groceryList)
// Possible output: ["Onions", "Apples"]
.removeAll()
This method empties the Set of all its values.
var groceryList: Set = ["Onions", "Apples", "Pasta"]
groceryList.removeAll()
print(groceryList)
// Output: []
.contains(_:)
This method checks if the Set contains a specific element.
var numbers: Set = [3, 63, 27]
let containsTwentySeven = numbers.contains(27)
print(containsTwentySeven)
// Output: true
.isEmpty
This property checks if the Set is empty and returns a boolean result.
var numbers = [3, 63, 27]
print(numbers.isEmpty) // Output: false
Sets operations
.union(_:)
This method returns a new set containing all elements from both sets. Since sets cannot have duplicate values, any value that appears in both sets will only appear once in the union.
let fellowshipOfTheRing: Set = ["Frodo", "Sam", "Merry", "Pippin", "Aragorn", "Legolas", "Gimli", "Boromir", "Gandalf"]
let charactersInRohan: Set = ["Aragorn", "Legolas", "Gimli", "Gandalf", "Eomer", "Eowyn", "Theoden"]
let allCharacters = fellowshipOfTheRing.union(charactersInRohan)
print(allCharacters)
// Possible output: ["Sam", "Merry", "Pippin", "Legolas", "Aragorn", "Gimli", "Eowyn", "Frodo", "Theoden", "Eomer", "Boromir", "Gandalf"]
.intersection(_:)
This method returns a new set with only the elements common to both sets.
let fellowshipOfTheRing: Set = ["Frodo", "Sam", "Merry", "Pippin", "Aragorn", "Legolas", "Gimli", "Boromir", "Gandalf"]
let charactersInRohan: Set = ["Aragorn", "Legolas", "Gimli", "Gandalf", "Eomer", "Eowyn", "Theoden"]
let commonCharacters = fellowshipOfTheRing.intersection(charactersInRohan)
print(commonCharacters)
// Possible output: ["Aragorn", "Legolas", "Gandalf", "Gimli"]
.subtracting(_:)
This method returns a new set with the elements of the first set that are not in the second set.
let fellowshipOfTheRing: Set = ["Frodo", "Sam", "Merry", "Pippin", "Aragorn", "Legolas", "Gimli", "Boromir", "Gandalf"]
let charactersInRohan: Set = ["Aragorn", "Legolas", "Gimli", "Gandalf", "Eomer", "Eowyn", "Theoden"]
let uniqueToFellowship = fellowshipOfTheRing.subtracting(charactersInRohan)
print(uniqueToFellowship)
// Possible output:["Boromir", "Frodo", "Pippin", "Sam", "Merry"]
.symmetricDifference(_:)
This method returns a new set with elements that are in either of the sets but not in both.
let fellowshipOfTheRing: Set = ["Frodo", "Sam", "Merry", "Pippin", "Aragorn", "Legolas", "Gimli", "Boromir", "Gandalf"]
let charactersInRohan: Set = ["Aragorn", "Legolas", "Gimli", "Gandalf", "Eomer", "Eowyn", "Theoden"]
let differentCharacters = fellowshipOfTheRing.symmetricDifference(charactersInRohan)
print(differentCharacters)
// Possible output:["Pippin", "Boromir", "Eomer", "Merry", "Sam", "Frodo", "Eowyn", "Theoden"]
Resources
If you want a Cheat Sheet with some of these methods and properties, feel free to save or download this image. If you share it please do not delete or hide my name π«Άπ»β
Also if you want to keep learning more about this I highly recommend checking the official documentation and courses here
Want to keep learning about Swift?
This a full series on Swift 101, next chapter will be the third part of Collections where I will share about Tuples and Dictionaries, so I hope to see you there!
If you enjoyed this, please share, like, and comment. I hope this can be useful to someone and that it will inspire more people to learn and code with Swift
Posted on June 10, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.