4️⃣Data Structures
Fall 2023 | Vin Bui
Last updated
Fall 2023 | Vin Bui
Last updated
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.
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.
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:
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.
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.
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.