4️⃣Data Structures

Fall 2023 | Vin Bui

We learned how to use variables and constants to store data, but only explored basic values such as integer numbers and text. However, when we program, we often need to hold more complicated data that requires a specialized format for organizing and retrieving the data. To do this, we use Data Structures.

Arrays

The most common data structure that we will be using is an array. Arrays store a group of values together into a single collection, and we can access these values using their position in the array.

var staff = ["Vin", "Richie", "Tiffany", "Jennifer", "Antoinette", "Elvis"]
staff[0]
staff[1]
staff[2]

We use square brackets [] to mark the start and end point of the array and use commas , to separate each value.

Swift uses type inferencing to determine the type of staff. Because all of the elements inside of the array are strings, Swift knows that staff is an array of strings (Array<String>). If we change the value of an element to a different type, our code will not compile.

Instead of letting Swift infer what types our array will hold, we can specify the type that we want.

As we can see, if we put in a value that does not match with the given type, our code will not compile.

However, it is possible to allow our arrays to hold any type. We can give it the special Any data type:

When adding values to our array, we must first initialize it with an original value. The following code will not compile:

We can initialize our array in the following ways:

var staff: [String] = []
var staff = [String]()

Notice that we used an append method to add elements to the end of the array. Swift provides many methods that we can use on our array, and we can even add our own! We can also use operators such as + to glue arrays together and return a new array. Read more about them in the Apple Documentation.

Dictionaries

Another common data structure that we might encounter are called dictionaries. These are similar to arrays except we use a key to access a value in the collection. In other words, dictionaries store key-value pairs.

var staffAge: [String: Int] = ["Vin": 19, "Richie": 20, "Antoinette": 4]

It is also common to break up our dictionary like so to keep things readable:

Similar to arrays, Swift provides a lot of methods that we can use with dictionaries. The Apple Documentation provides more information about them.

Last updated