Arrays In Swift Explained

Written by Reinder de Vries on November 22 2018 in App Development

Arrays In Swift Explained

Arrays are fundamental building blocks of apps. In this article you’ll learn how you can use arrays in your Swift code. We’ll discuss:

  • How to create arrays, with literal syntax and initializers
  • How you can modify an array by adding, removing and replacing elements
  • How to iterate over array elements by using a for loop

Ready? Let’s go.

  1. Creating An Array
  2. Adding And Removing Array Items
  3. Getting And Changing Array Items
  4. Looping Over An Array
  5. Further Reading

Creating An Array

In computer programming, arrays are numbered lists of items with the same type. A variable contains one value, and an array can hold many values. Let’s get started with the syntax to create an array.

Here’s an example:

let names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"]
print(names)

In the above code, two things happen:

  • First, we’re creating an array with the [...] array literal. This array is assigned to the constant names.
  • Then, we’re printing out the value of names. This outputs the array to the Console or debug area.

So, what’s a literal? A literal value is an expression that is to be used exactly as it is – that’s why it’s called a “literal”. In Swift, literals help you constuct code without using complex syntax.

A few examples of literals:

let age  = 42
let pi   = 3.1415
let name = "Bob"

The array literal starts with an opening square bracket [, followed by zero, one or more array elements, and a closing square bracket ]. Like this:

let months:[String]     = ["January", "February", "March"]
let scores:[Int]        = [1, 5, 11, 18]
let fractions:[Double]  = [1/2, 2/3, 3/4, 4/5, 5/6]

Array’s have fixed types, just like any other variable in Swift. That means that every element in an array has the same type, that cannot be changed once set.

In the above examples, every array item has a fixed type: String, Int and Double. Therefore, the types of the months, scores and fraction arrays are [String], [Int] and [Double] respectively.

Thanks to type inference, you often do not have to explicitly provide the type of a variable when declaring it. Keep in mind that every variable in Swift has a type, even when you don’t explicitly provide it.

How do you create an empty array? Here’s how:

let score = [Int]()
print(score)

In the above example we’re using the array type [Int] together with parentheses (). This is called initializer syntax and it’s very similar to creating new objects, i.e. you use the object type in conjuction with ().

The [String] array type is a shorthand for Array<String>. And yes, you’ve guessed it right: arrays are generics!

Learn how to build iOS apps

Get started with iOS 12 and Swift 4

Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 4 and Xcode 10.

Adding And Removing Array Items

We’ve discussed before that arrays are essentially lists of items with the same type. Every array element has a numeric index, starting at 0. Let’s go back to that first example, this one:

var names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"]
print(names)

When we write out those array values, this is what you get:

names = (
    0: Arthur
    1: Ford
    2: Trillian
    3: Zaphod
    4: Marvin
)

Here’s how you add an item to the names array:

names.append("Eddie")

You use the append(_:) function to add a new item onto the end of the array. This item must have the same type as the other array items, i.e. String. And you can also use the addition assign operator += like this:

names += ["Heart of Gold"]

Fun Fact: You can combine two arrays of similar types with the addition operator +. As such, you’ll see in the above code that the += operator actually combines the names array with a new array of one element!

Can you also remove items from an array? Of course! You’ll need the index of that array element. Like this:

names.remove(at: 2)

This will remove the "Trillian" item from the array. And here’s something counter-intuitive: the "Trillian" element is the third item in the names array. Yet, it has index number 2 – why is that? It’s because arrays are zero-indexed. They start with index 0, so any n-th has index n - 1. Confusing? You’ll get used to it soon enough!

Inserting items into an array is similar to adding and removing items. Here’s how:

names.insert("Humma Kavula", at: 4)

This will insert the new name at index no. 4. This means that the item that was at position 4 will now shift one position to the right. It won’t get replaced.

Here’s an interactive Swift sandbox for you to play with:

var names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"]

names.append("Eddie")
names += ["Heart of Gold"]
names.remove(at: 2)
names.insert("Humma Kavula", at: 4)

print(names)

Getting And Changing Array Items

Here’s what we’ve discussed so far:

  • Creating arrays, and their types
  • Appending items to arrays
  • Removing items from arrays
  • Inserting items into arrays

Every one of these items involves array indices, and it’s worth it to discuss that. Indices are the numeric “labels” that every array item gets, starting at 0.

Array indices are consecutive, so you can’t insert an item at index 99 for an array that has only 10 items. Likewise, when you remove an item from an array, the items on the right of the removed item will shift one position to the left.

It’s easiest to imagine array items on a line, with the left side starting at 0. It then makes sense to think of “left” and “right”. Keep in mind that not every developer reads from left-to-right, though! Spending some time to get to know how array indices work will definitely help you learn iOS development better, and it’ll save you from some crazy bugs in the future.

Let’s get back to arrays. You can read items from an array by using the item index. Like this:

let user = names[2]
print(user)
// Output: Trillian

That names[2] part is called subscript syntax. You can access any array element this way, i.e. with array[index]. And we can also use it to modify an array. Like this:

names[2] = "Prostetnic Vogon Jeltz"

Here’s an interactive example:

var names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"]
names[2] = "Prostetnic Vogon Jeltz"

print(names)

Looping Over An Array

Arrays and loops are like Simon and Garfunkel – they go really well together. Before we start looping over arrays though, let’s check out some useful array properties:

  • array.count contains the number of elements in an array
  • array.first contains the first item of the array
  • array.last contains the last item of the array
  • array.isEmpty is true when the array is empty

You can use array.randomElement() to get a random element from the array (Swift 4.2+). And arrays have a large number of helper functions, like first(where:) and contains(_:).

Fun Fact: The last index of an array is equal to array.count - 1. Make sure you understand why! It’s got something to do with zero-indexing

OK, let’s get back to for loops. A for loop lets you iterate over any kind of sequence or collection, including arrays. Here’s an example:

let name = ...

for name in names {
    print(name)
}

The above code will output every item in names. Inside the for loop body you can use the local constant name. Every time the loop runs, an array item is assigned to name and the loop body is executed. This lets you do something, i.e. run some code, for every array item.

Let’s say you want to calculate the average score for an exam. Like this:

let scores = [8, 7, 9, 3, 4, 9, 7, 5, 8, 3, 5]
var sum = 0

for score in scores {
sum += score
}

print(Double(sum) / Double(scores.count))

Here’s how that code works:

  • First, we’re creating an array scores of type [Int] with a bunch of exam scores between 1 and 10. We’re also initializing a variable sum and set it to zero.
  • Then, we loop over every item in the scores array. Inside the loop, the array item is assigned to constant score. The score is added to sum with the += operator.
  • On the last line, we print out the result of sum / scores.count. We’re dividing the sum of scores by the number of scores, which gives us the average score. (We’re using Double() here so the result is a decimal-point number.)

Awesome! Let’s look at another example:

var names = ["Arthur", "Ford", "Trillian", "Zaphod", "Marvin"]
var reversed = [String]()

for name in names {
reversed.append(String(name.reversed()))
}

print(reversed)

With the above code we’re reversing the strings in the names array. A name like Arthur becomes ruhtrA. How does it work?

  • First, we’re initializing two arrays names and reversed. Both are of type [String].
  • Then, we’re looping over names. Every name is reversed and added to the reversed array.
  • Finally, we’re printing out the value of reversed.

Awesome!

Learn how to build iOS apps

Get started with iOS 12 and Swift 4

Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 4 and Xcode 10.

Further Reading

Arrays are one of the basic building blocks of apps, so it’s crucial to learn about them if you want to master iOS development. Here’s what you’ve learned in this article:

  • How to create arrays, using literal syntax and initializers
  • Swift code to change, insert and remove array items
  • How to iterate array items with a for loop

Arrays will make more sense when you work with them, so I definitely recommend you check out some of my more intermediate articles about arrays:

Reinder de Vries

Reinder de Vries

Reinder de Vries is a professional iOS developer. He teaches app developers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed a few dozen apps for iOS, worked for global brands and lead development at several startups. When he’s not coding, he enjoys strong espresso and traveling.