Collection Types in Swift

Beside variables and constants containing single values, they can also contain multiple values. This is what we like to call Collection Types. Collection Types have the ability to have multiple values stored inside a variable or a constant. This makes it really powerful to use when we need to work with a lot of data.

article

Beside variables and constants containing single values, they can also contain multiple values. This is what we like to call Collection Types. Collection Types have the ability to have multiple values stored inside a variable or a constant. This makes it really powerful to use when we need to work with a lot of data.


What are Collection Types?


Swift's collection types are essential for managing groups of values. Arrays organize elements in a specific order, allowing for duplicate values and enabling indexing. Sets, in contrast, store unique values without any order, perfect for checking membership or removing duplicates efficiently. Dictionaries hold key-value pairs, facilitating fast retrieval of values based on unique keys. These collections are mutable, supporting operations like adding, removing, or modifying elements, and are type-safe, ensuring that all elements adhere to a specific data type.


Let's look at the syntax of Arrays for now. When we declare an Array we actually use a var or let keyword followed by the name of the collection and then we use the = key ending with []. But for safety it would be better to actually declare what kind of values the Array should contain. In the next example we declare three different arrays so we can see the difference between an empty array and a array where we actually declare the value type.


    
        var fruits = [] // This array is a empty array where we didn't specify a valye type
        var vegetables: [String] = [] // This array can only contain Strings
        var numbers: [Int] = [] // This array can only contain Integers
    

In the above code example, we created 3 different arrays. The first array is only an empty array where we can actually store anything we want. The second array can only contain Strings, the compiler will throw an error if we add something that is not a string value. And last but not least we have an array of Integers which can only contain Integer Values. Let's create a new array in the following example and add some values to play with.


    
        var dairy: [String] = ["milk", "yoghurt", "quark", "cream cheese"]
    

So now we have some milk products to work with, we are going to play around with the array while learning something new. We are going to learn how we can display all the values using String Interpolation. With String Interpolation we can actually paste strings inside a print statement so we can display the values inside our array in our console or in our right screen in the playground.


    
        print(\(dairy))
    

In the above example we print out all the values in our console at ones. Of course this is very cool because we now actually see the values from our dairy array. But what if we only want to select or print out one specific item from our array? Well to do that we can actually use the specific index of n array value. The index of a value is actually the place of the value inside of the array. In an array every index always starts at 0. So the first value in our array is milk. And milk has an index of 0, because it is at the start of the array. So the next value inside the array, yoghurt will get a index of 1 and so on. This is probably a little bit confusing if you are a novice or even beginner developer. But believe me when i say that it will make sense after a while. So when we want to select a specific value inside our array we can call the array and add [] behind it with the value's index in it. So when we want need the milk we use dairy[0] like in the following example.


    
        dairy[0]
        print(\(dairy[0]))
    

Adding values to an Array

Now we learned how we can retrieve values from an array, we also want to know how we can actually add new values to our array. Adding new values to an array can be really handy if you want to extend or replace values inside your array. Adding values to an array can be done using the .append keyword.


    
        dairy.append("Sour Cream")
        dairy.append("Double Cream")
        print(dairy)
    

Now when we print our array we see the new values appear as well. This is actually a really easy and cool way of working with Arrays. But what if we want to delete a specific value from the Array? Well just like adding values to an array, we can also delete a value from an array.


    
        dairy.remove(at: 1) // This removes the value yoghurt from the array
        print(dairy)
    

Dictionaries in Swift


When we need to work with more delicate information, like for example keys that have a value, we can use dictionaries. Dictionaries are a collection type where we have a key and the key has a value. Dictionaries are mostly used when we work with internet or network data which we receive from an API. For example. Let's say we have a PokeDex app and we want to retrieve information about Bulbasaur. You will probably want to have multiple kinds of information, so it would look a little bit like this.


    
        var bulbasaur: [String: Any] = [
            "name": "Bulbasaur",
            "type": "Grass",
            "moves": "4",
            "evolutions": "2"
        ]
    

In the above code example you see a really simplyfied dictionary of Bulbasaur. We declare a variable called bulbasaur and we tell it that it is a dictionary that has String keys , and the values van be anything. Inside the Dictionary you see different keys, each with it's own value. This is actually what a dictionary is, a collection of information. So now we have our Dictionary, lets play around with it and see what we can do with it. Just like with Arrays, we can return specific values from the Dictionary by calling the key.


    
        var bulbasaur: [String: Any] = [
            "name": "Bulbasaur",
            "type": "Grass",
            "moves": "4",
            "evolutions": "2"
        ]

        let name = bulbasaur[name]
        print(name)
    

This piece of code allows us to print the name of bulbasaur. This happens because we actually call the key "name" inside our dicrionary and retrieve its value. Let's expand this so we can actually do something fun with this.


    
        var bulbasaur: [String: Any] = [
            "name": "Bulbasaur",
            "type": "Grass",
            "moves": "4",
            "evolutions": "2"
        ]

        let name = bulbasaur[name]
        let type = bulbasaur[type]
        let moves = bulbasaur[moves]
        let evolutions = bulbasaur[evolutions]

        print("\(name) is a \(type) type pokemon and it can learn up to \(moves) and has \(evolutions) evolutions.")
    

In the above code we were able to actually print a complete sentence with all the information of the dictionary. This by calling the values and use string interpolation.

Updating and Deleting values in a Dictionary


Besides of retrieving information from a dictionary, we can also update, delete and add new values to our dictionary by doing the following.


    

        // Adding new values to our Dictionary
        bulbasaur["height"] = 2.2
        bulbasaur["weight"] = 20

        // Updating a certain value using subscript

        bulbasaur[type] = "Grass/ Poison"

        // Updating a certain value using .updateValue

        bulbasaur.updateValue("IvySaur", forKey: "name")
    

In the above code, you see how we can add and update our dictionary and its values. I think the adding part speaks for itself but as you see, we have 2 different ways to update our dictionary. Thie first one is the use of subscript. 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.


Just as updating, deleting values is also really easy in Swift


        
    
            // Adding new values to our Dictionary
            bulbasaur["height"] = 2.2
            bulbasaur["weight"] = 20
    
            // Deleting a certain value using subscript
    
            bulbasaur[type] = nil
    
            // Updating a certain value using .updateValue
    
            bulbasaur.removeValue(forKey: "name")
        
    

Conclusion


In this article, we learned about Arrays and Dictionaries and how to work with them. As you see, they are really easy to use and actually really powerful in day to day tasks. Arrays and Dictionaries are actually the most used Collection Types in Swift, but there is one more we will talk about in another article called Sets.

instructor

Exodai INSTRUCTOR!

Johan t'Sas

Owner and Swift developer!