An Introduction to Swift
Collections

Two of the primary collection types in Swift are Arrays and Dictionaries.

Array

Arrays store data of the same type in an ordered list.

The following code creates an empty Array which stores Strings.

var listOfStrings = [String]()

If we want to let Swift infer the type of our Array, we can create it and populate it with some entries as follows:

var someStrings = ["Wallace", "Gromit", "Cheddar"]

The items inside of an Array are accessed via indexes. The index represents its position in the array. We always start the count from 0.

var someStrings = ["Wallace", "Gromit", "Cheddar"]

print(someStrings[1])

The above code outputs "Gromit" .

Dictionary

Dictionaries store unordered key-value pairs, where all keys are of the same type and all values are of the same type.

We can create an empty dictionary which maps from String keys to Int values as follows:

var romanToDecimal = [String: Int]()

And now to create some mappings we can do the following:

romanToDecimal["X"] = 10

romanToDecimal["V"] = 5

A Note on Performance

Dictionaries provide instant look-up time. If we want to check if a key is present in a dictionary, all we do is check if there is a mapping for the key to a value. In big O notation, a notation used to describe the worst-case runtime of a piece of code, we would write this as O(1).

If we want to check if a value is present in an array, we need to cycle through the array and examine each element individually. In big O, it is written as O(n). This is to say that our runtime is bounded by the number of elements (n) in the array.

Mutability

Assigning a collection to a variable means that the collection can be changed later on.

var someList = [1,2,3]

someList = [1]

If instead, the collection is assigned to a constant, the collection and its contents cannot be changed.
[]
['Programming', 'Coding', 'iOS', 'Technology', 'Swift']