Swift - Collections
Tags: swift, beginners, programming
Published: 2021-12-27 15:51:51

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

![collections](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnyy4remlojlsfxjygf3.png)
 
## Arrays
An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

### creating empty array
```swift
var arr:[Int] = []
```

### Accessing and modifying the array
- number of elements in an array -> **count** method
- to check the array is empty -> **isEmpty** method
- to add new item to end -> **append** method (+=)
- to retrieve a value from array using subscript syntax -> **arr[0]**
- to insert at a particular location -> **insert(_at:)** method
- to remove at a particular location -> **remove(_at:)** method
- to remove the last element -> **removeLast()** method

## Iterating over an array
we can iterate over the entire set of values using the for-in loop

```swift
var shoppingList = ["milk","bread","eggs"]
for item in shoppinglist {
print(item)
}
//milk
//bread
//eggs
```
- If you need the index value, use the enumerated() method to iterate over the array instead.For each item in the array, the enumerated method returns a tuple composed of an integer and an item.

```swift
for (index,value) in shoppingList.enumerated() {
print("\(index) : \(value)")
}
//0 : milk
//1 : bread
//2 : eggs
```
## Sets
A set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items isn’t important, or when you need to ensure that an item only appears once

### creating set
```swift
//Empty set
var letters = Set<Characters>()

//Using array literals
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
```
## Accessing and modifying set
- Count the total items in set -> **count** method
- to check the set is empty or not -> **isEmpty** method
- to insert new item -> **insert(_:)** method
- to remove a particular Item -> **remove(_:)** method

## Iterating over set
You can iterate over the values in a set with a for-in loop.
```swift
for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop
```
Swift’s Set type doesn’t have a defined ordering. To iterate over the values of a set in a specific order, use the sorted() method, which returns the set’s elements as an array sorted using the < operator.
```swift
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz
```
## Set operations
![Set operations](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a66ck1kpk3c7sv8uzx3v.png)
 
- Use the intersection(_:) method to create a new set with only the values common to both sets.
- Use the symmetricDifference(_:) method to create a new set with values in either set, but not both.
- Use the union(_:) method to create a new set with all of the values in both sets.
- Use the subtracting(_:) method to create a new set with values not in the specified set.

## Dictionary 
A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary.

### Creating an Dictionary
```swift
var namesOfIntegers: [Int: String] = [:]
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
```
### Accessing and modifying 
- Count the total items in Dictionary  -> **count** method
- to check the Dictionary  is empty or not -> **isEmpty** method

You can add a new item to a dictionary with subscript syntax. Use a new key of the appropriate type as the subscript index, and assign a new value of the appropriate type:

```swift
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

```
You can also use subscript syntax to change the value associated with a particular key:

```swift
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
```

As an alternative to subscripting, use a dictionary’s updateValue(_:forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(_:forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(_:forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.

## Iterating over dictionary 
You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

```swift
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson
```
You can also retrieve an iterable collection of a dictionary’s keys or values by accessing its keys and values properties:

```swift
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ

for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson
```