Skip to content

Arrays and Dictionaries

Grouping data and variables

  • Lesson
  • 2 min read
  • 1 of 7 in this chapter

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 an index of 0, 4 has an index of 1, and so on and so on.

Swift
var evenNumbers = [2,4,6,8,10]
var names = ["Greg","Fregley","Rowley"]
print(evenNumbers[0]) // prints 2
print(names[2]) // prints "Rowley"

Specifying Array Data Types

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

Swift
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.

Swift
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.

Swift
var fullNames = [
"Greg": "Heffley", 
"Rowley": "Jefferson", 
"Rodrick": "Heffley"
]
 
print(fullNames["Rodrick"]) // prints "Heffley"
print(fullNames["Rowley"]) // prints "Jefferson"