Swift 101: Collections Part II - Sets
Tags: swift, beginners, learning, mobile
Published: 2024-06-10 16:46:53

#<h1> Hola Mundo! </h1>
<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 first part of collections which was arrays](https://dev.to/silviaespanagil/swift-101-collections-part-i-arrays-2a52). 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](https://dev.to/silviaespanagil/swift-101-collections-part-i-arrays-2a52), "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**✨​.

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

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


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

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

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

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

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

```swift
var groceryList: Set = ["Onions", "Apples", "Pasta"]
groceryList.removeAll()
print(groceryList) 
// Output: []
```

####`.contains(_:)`
This method checks if the Set contains a specific element.

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

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

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

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

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

```swift
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 🫶🏻​

![Cheat sheet with some of the methods and properties of setss](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nj1somt6jysgyhptjawt.png)

Also if you want to keep learning more about this I highly recommend checking the official documentation and courses [here](https://developer.apple.com/learn/)

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