Swift 101: Collections part III - Tuples and Dictionaries

silviaespanagil

Silvia España Gil

Posted on June 17, 2024

Swift 101: Collections part III - Tuples and Dictionaries

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 second part of collections which was sets. Next week, I'll share the last part of collections with Enums!

So, let's get to it 💪​!


As a quick refresher, "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 and Sets which we already discussed. Today, let's talk about ​​✨Tuples and Dictionaries​✨​.


Tuples


Tuples are a collection type that allows us to group multiple values into a single compound value. These values can be of different types, making tuples a flexible way to group related values together.

Here are some important characteristics and rules about tuples in Swift:

  • Fixed Size: The number of elements in a tuple is fixed when you create it. You cannot add or remove elements after the tuple is created.

  • Immutable Types: While you can change the values within a tuple, you cannot change the types of the elements. The types of the elements are defined when the tuple is created and must remain the same.

How to declare a Tuple

Declaring a tuple in Swift is really easy. You simply enclose the elements in parentheses and separate them by commas. You can also name the elements for easier access.

Here's an example of how to declare and use a tuple:


var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
print(character) 
// Output: (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
Enter fullscreen mode Exit fullscreen mode

❌​​ You can't declare an empty tuple, because of the characteristics previously explained. Doing so will show an error in Xcode❌​


Tuples Managing: Accessing Values

Modifying Tuples

As with any variable, we can change the values of our Tuple. However, one of the main characteristics of the Tuples is that we cannot change their elements or types.

To update a Tuple, we can do:


 character = (name: "Arwen", nickname: "Undomiel", ageOfDeath: 2901)
Enter fullscreen mode Exit fullscreen mode

Attempting to assign values differently will result in an error:


 character = (name: "Frodo")
// Error: cannot assign value of type '(name: String)' to type '(name: String, nickname: String, ageOfDeath: Int)'
Enter fullscreen mode Exit fullscreen mode
Accessing Tuples

To access a tuple value, we must only take the name of the variable and reference the element we want to access.

var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
print(character.name)
// Output: Aragorn
Enter fullscreen mode Exit fullscreen mode

We can also access one element of our Tuple and then change its value, while the rest of the elements remain with the old value.

var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)

character.name = "Aragorn, son of Arathorn"
print(character.name)
// Output: Aragorn, son of Arathorn
print(character)
// Output: (name: "Aragorn, son of Arathorn", nickname: "Strider", ageOfDeath: 219)
Enter fullscreen mode Exit fullscreen mode

Tuples methods and properties

Tuples in Swift do not have any properties or methods. They are a value type that only groups values. However, there are a couple of operations possible with tuples:

Access to elements

We already showed that we can access an element using its name, but we can also do so using the index

var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)

print(character.name)
// Output: Aragorn

print(character.1)
// Output: Aragorn
Enter fullscreen mode Exit fullscreen mode

Decomposition

You can decompose the tuple into separated variables

let (name, nickname, ageOfDeath) = character

print(name) // Output: Aragorn
print(nickname) // Output: Strider
print(ageOfDeath) // Output: 219
Enter fullscreen mode Exit fullscreen mode

Comparison

You can compare tuples if the elements are comparable.

var character = (name: "Aragorn", status: "Married")

let anotherCharacter = (name: "Arwen Undomiel", status: "Married")

print(character == anotherCharacter) // Output: false

print(character.status == anotherCharacter.status) // Output: true
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Dictionaries are another collection type available in Swift. Dictionaries are stored not in a numeric position (index) but with a key.

How to declare a Dictionary

To declare a dictionary, we must specify the key type inside brackets [ ] and the value using a colon.

var emptyDictionary = [String: String] = [:]
emptyDictionary["keyName"] = "Value"
print(emptyDictionary) //Output:["keyName": "Value"]

var characterDetails = [
"Aragorn": "Son of Arathorn, also known as Strider",
"Frodo": "Bearer of the One Ring",
"Gandalf": "The Grey, later known as Gandalf the White"
]

print(characterDetails["Aragorn"])
// Output: Son of Arathorn, also known as Strider
Enter fullscreen mode Exit fullscreen mode

Dictionaries Managing: Accessing Values

Accessing values with iterations

We can access dictionary values by iterating on their values. When iterating through a dictionary, both keys and values can be accessed if needed.


var characterDetails = [
"Aragorn": "Son of Arathorn, also known as Strider",
"Frodo": "Bearer of the One Ring"
]

for (key, value) in characterDetails {
  print("\(key) also known as \(value)")
}
/* Possible output:
Aragorn also known as Son of Arathorn, also known as Strider
Frodo also known as Bearer of the One Ring*/
Enter fullscreen mode Exit fullscreen mode

💢​Note that when iterating over Dictionaries in Swift, the elements may be returned in an unordered manner for efficiency reasons.💢

Accessing values using the key

We may access a dictionary using the key name if we know it in advance.

print(characterDetails["Aragorn"])
//Output: Son of Arathorn, also known as Strider
Enter fullscreen mode Exit fullscreen mode

We may also store all the keys or all the values in a new collection to use.

let characterNames = characterDetails.key
print(characterNames)
//Output: ["Frodo", "Aragorn"]

let characterDescription = characterDetails.values
print(characterDescription)
//Output: ["Son of Arathorn, also known as Strider", "Bearer of the One Ring"]
Enter fullscreen mode Exit fullscreen mode

Adding new values to an existing dictionary

To add a new value to an existing dictionary we should follow the next syntax dictionaryName[NewKey] = NewValue

var characterDetails = [
"Aragorn": "Son of Arathorn, also known as Strider",
"Frodo": "Bearer of the One Ring"
]

//New value
characterDetails["Galadriel"] = "Lady of Lothlórien, Nenya bearer"

print(characterDetails)
//Output: ["Frodo": "Bearer of the One Ring", "Galadriel": "Lady of Lothlórien, Nenya bearer", "Aragorn": "Son of Arathorn, also known as Strider"]
Enter fullscreen mode Exit fullscreen mode

Dictionaries methods and properties

.updateValue(): Allows us to update the value of an existing key

characterDetails.updateValue("Just a hobbit", forKey: "Frodo")
print(characterDetails["Frodo"])
//Output: "Just a hobbit"
Enter fullscreen mode Exit fullscreen mode

.remove(): Allows us to remove a value completely from our dictionary.

characterDetails.removeValue(forKey: "Frodo")
print(characterDetails)
//Output: ["Aragorn": "Son of Arathorn, also known as Strider", "Galadriel": "Lady of Lothlórien, Nenya bearer"]
Enter fullscreen mode Exit fullscreen mode

.removeAll(): Allow us to remove all the values in the dictionary.

characterDetails.removeAll()
print(characterDetails)
//Output: [:]
Enter fullscreen mode Exit fullscreen mode

.isEmpty(): Returns a boolean reflecting if the dictionary is empty or not

print(characterDetails.isEmpty)
//Output: true
Enter fullscreen mode Exit fullscreen mode

.count(): Count all the elements inside the dictionary

var characterDetails = [
"Aragorn": "Son of Arathorn, also known as Strider",
"Frodo": "Bearer of the One Ring"
]
print(characterDetails.count)
//Output: 2
Enter fullscreen mode Exit fullscreen mode

Want to keep learning about Swift?

This a full series on Swift 101, next chapter will be the final part of Collections where I will share about Enums, so I hope to see you there!

Remember that you can always go further into this information by checking the official documentation and courses here

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

💖 💪 🙅 🚩
silviaespanagil
Silvia España Gil

Posted on June 17, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related