Swift 101: Collections part III - Tuples and Dictionaries
Tags: swift, beginners, learning, mobile
Published: 2024-06-17 13:38:39

#Hola Mundo!
<Enter>

Welcome to a new article in a series of [Swift 101 notes](https://dev.to/silviaespanagil/swift-101-getting-into-ios-development-gji) 📝  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](https://dev.to/silviaespanagil/swift-101-collections-part-ii-sets-3i41). 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​**✨​.

<Enter>
___
###Tuples
<Enter>
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.

<Enter>

####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:

```swift

var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
print(character) 
// Output: (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
```

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


<Enter>
___
### 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:

```swift

✅ character = (name: "Arwen", nickname: "Undomiel", ageOfDeath: 2901)
```

Attempting to assign values differently will result in an error:

```swift

❌ character = (name: "Frodo")
// Error: cannot assign value of type '(name: String)' to type '(name: String, nickname: String, ageOfDeath: Int)'
```

<Enter>

##### **Accessing Tuples**

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

```swift
var character = (name: "Aragorn", nickname: "Strider", ageOfDeath: 219)
print(character.name)
// Output: Aragorn
```

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. 

```swift
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>
___
#### 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:

<Enter>

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

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

print(character.name)
// Output: Aragorn

print(character.1)
// Output: Aragorn
```
####Decomposition
You can decompose the tuple into separated variables

```swift
let (name, nickname, ageOfDeath) = character

print(name) // Output: Aragorn
print(nickname) // Output: Strider
print(ageOfDeath) // Output: 219
```

<Enter>

####Comparison 
You can compare tuples if the elements are comparable.

```swift
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>
___
###Dictionaries
<Enter>

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. 

```swift
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>
___
### 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.

```swift

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*/
```

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

<Enter>
#### Accessing values using the key
We may access a dictionary using the key name if we know it in advance.

```swift
print(characterDetails["Aragorn"])
//Output: Son of Arathorn, also known as Strider
```

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

```swift
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>

#### 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`

```swift
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>
___
### Dictionaries methods and properties

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

```swift
characterDetails.updateValue("Just a hobbit", forKey: "Frodo")
print(characterDetails["Frodo"])
//Output: "Just a hobbit"
```
<Enter>

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

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

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

```swift
characterDetails.removeAll()
print(characterDetails)
//Output: [:]
```

<Enter>

#### **`.isEmpty()`:** Returns a boolean reflecting if the dictionary is empty or not
```swift
print(characterDetails.isEmpty)
//Output: true
```

<Enter>

#### **`.count()`:** Count all the elements inside the dictionary
```swift
var characterDetails = [
"Aragorn": "Son of Arathorn, also known as Strider",
"Frodo": "Bearer of the One Ring"
]
print(characterDetails.count)
//Output: 2
```
<Enter>
___
###Want to keep learning about Swift? 
This a full series on [Swift 101](https://dev.to/silviaespanagil/swift-101-getting-into-ios-development-gji), 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](https://developer.apple.com/learn/)

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