Back to blog

Arrays in Swift Explained


Aasif Khan
By Aasif Khan | Last Updated on May 6th, 2023 1:12 pm | 4-min read

Arrays are fundamental building blocks of apps. In this app development tutorial 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

Creating an Array

In computer programming, arrays are numbered lists (or “collections”) 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 […] literal syntax. 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.

What’s a literal? A literal value is an expression that’s used exactly as it is. It’s why they’re 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”

In the above code, we’re creating 3 constants with 3 literal values: an integer, a double and a string. You’re looking at the literal values of these types; that’s why they’re called literals. You’re literally writing integers, doubles and strings in your code.

Back to arrays. The array literal starts with an opening square bracket [, followed by zero, one or more 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. All array elements must have the same type, too.

In the above examples, every 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 (), like let tweet = Tweet().

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

Adding and Removing Array Items

We’ve discussed before that arrays are essentially collections of items with the same type. Every 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 their indices and 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 items in the collection, i.e. String. 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 the item for that. Like this:

names.remove(at: 2)

This will remove the “Trillian” item from the array, because that’s the item with index no. 2.

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 item 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; we’re inserting an item.

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 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”. 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]. 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’re great on their own, but also 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+). Arrays have a few other useful functions, like first(where:) and contains(_:). You can also manipulate arrays with higher-order functions like map(_:) and filter(_:).

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 names = [“Arthur”, “Ford”, “Trillian”, “Zaphod”, “Marvin”]

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 as the current item. Every time the loop runs, an item from the names collection is assigned to name and the loop body is executed. This let’s you execute some code for every item in the collection.

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
}

let average = Double(sum) / Double(scores.count)
print(average)

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 current collection 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 converting to 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!

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 tutorial:

  • 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 are part of collections in Swift. We’ve got a few collection types, such as:

  • Dictionaries
  • Sets
  • Tuples


Aasif Khan

Head of SEO at Appy Pie

App Builder

Most Popular Posts