Arrays and Dictionaries

Grouping data and variables

What are arrays?

An array is used to group certain information together. They are ordered, and the information in them can be changed. We can make them of any specific data type.

How do we create an array?

To create an array, it's the same as creating a normal variable, except we use square brackets and separate data with commas. To call each value, we write the array name, put brackets, and the index value. Index values start at 0, not 1. So in the example below, the value 2 has a index of 0, 4 has an index of 1, and so on and so on.

var evenNumbers = [2,4,6,8,10]
var names = ["Greg","Fregley","Rowley"]

Specifying Array Data Types

Just like we need to specify empty variables, we need to specify empty arrays, like so:

var colors: [String]
colors = ["red","blue","yellow","green"]

This is not only restricted for strings, we can make arrays of ANY data type. We can even make arrays of multiple data types, which usually wouldn’t be needed, but does have it’s usage.

var random: [Any] = [2,"blue",true]

What are dictionaries?

Another way to group information in Swift is through a dictionary. A dictionary consists of keys and values. The key is on the left side, and the value is on the right. Dictionaries allow us to create more descriptive lists. Instead of accessing a value by an index number, we can access it using a descriptive ‘key’. It’s very similar to writing an array.

var fullNames = [
"Greg": "Heffley", 
"Rowley": "Jefferson", 
"Rodrick": "Heffley"

What's next?

Next, we will start to evaluate conditions using booleans, with if statements.