Swift Arrays: The Most Used Collection to Organize Data

Arrays are the most commonly used data type in Swift and other programming languages. You will often use arrays to organize your app’s data as they are the most versatile data structure.

This article will explore the most common features of arrays in Swift.



Architecting SwiftUI apps with MVC and MVVM

GET THE FREE BOOK NOW

Table of contents

Store multiple elements of the same type based on their index with arrays

Arrays are data collections that store multiple elements of the same type based on their index. They are compelling data structures that are relatively easy to use.

Let’s start with a basic example.

let scores = [11,20,30,40,51]

The scores array stores the scores for the levels of a game. The array’s elements are separated by commas and placed between square brackets.

Type inference doesn’t work for empty arrays.

let emptyScores = []

An empty array doesn’t have any elements between its square brackets.

The compiler flags an error for the code because it doesn’t know the type of the array’s elements. The elements of an empty array may be of any given type. So you need to mention the elements’ type to avoid the error.

let emptyScores: [Int] = []

emptyScores is of type [Int], so the error disappears. The type of the array’s Int elements is placed between square brackets.

Arrays can also have elements of optional types.

let noScores: [Int?]? = nil

noScores is an optional [Int?]? array and its elements have optional Int? values.

Access elements in arrays using indices

The index of an array’s element starts with 0 and goes to the number of elements in the array minus 1. This guarantees a unique index for every element in the array.

let scores = [11,20,30,40,51]
scores[0] = 10
print("The first level's score is \(scores[0]).")

This code uses the index of the first element in the scores array to change the element’s value in the array. The index is placed between square brackets, and the element’s updated value is retrieved from the array with string interpolation.

The code crashes if you use an invalid index to access an array’s element.

let scores = [11,20,30,40,51]
scores[5] = 50

The scores array has five elements, so 5 is not a valid index for any elements in the array. Unfortunately, that’s a mistake the compiler cannot spot since it’s syntactically correct.

But when your program tries to access an invalid array index at runtime, it causes a fatal error that crashes it. If you run that piece of code in an Xcode playground, you will see an error that says Execution was interrupted.

Add elements to mutable arrays

You can quickly determine the current number of elements in an array at any time.

let scores = [11,20,30,40,51]
print("The array has \(scores.count) elements.")

The code uses the count computed property with string interpolation to determine the number of elements in the scores array.

You can change the number of elements by adding new ones to the array.

var scores = [11,20,30,40,51]
scores.append(60)

The append() method adds an element at the end of a mutable array.

You can also add an entire array to a mutable array.

var scores = [11,20,30,40,51]
scores += [70,80]

The addition assignment operator appends another array to the scores array.

Remove elements from mutable arrays

You can also change the number of elements in the array by removing existing elements from the array.

var scores = [11,20,30,40,51]
scores.remove(at: 2)

The remove(at:) method removes an element at a specific index from a mutable array. The compiler flags a runtime error if the index isn’t valid.

var scores = [11,20,30,40,51]
scores.remove(at: 5)

The scores array has five elements, so 5 does not work.

You can also remove all elements from a mutable array in one go.

var scores = [11,20,30,40,51]
scores = []

The above code assigns the scores array to an empty array to remove all its elements.

Check if an array is empty with array properties

You can check whether the previous array is empty.

let scores = [11,20,30,40,51]
if scores.isEmpty {
	print("Empty array!")
}

This code uses the isEmpty property to test if the scores array is empty. You can also do this by checking whether the number of elements in the array is 0.

let scores = [11,20,30,40,51]
if scores.count == 0 {
	print("Empty array!")
}

This code uses the count property to test whether the number of elements in the scores array is 0.

This approach iterates through all the elements in the array to determine their number first. So the previous approach is better as it’s more efficient overall.

Loop through the elements of arrays with for loops

For loops give you access to all the elements of an array at once.

The score constant stores the game’s current level’s score in the scores array. Each loop iteration updates the game’s score with the current level’s score.

You can also use loops to access all the corresponding indices for all elements in the array in just one go.

let scores = [10,20,30,40,50,60,70]
for (level, score) in scores.enumerated() {
	print("The score of level \(level + 1) is \(score).")
}

The enumerated() method returns a tuple that contains both the index and value of the current element in the scores array. You use the tuple with string interpolation to print the number and current score of each game level.

You may use wildcards with loops if you don’t care about the indices or the values of the elements in the array.

let scores = [10,20,30,40,50,60,70]
for _ in scores {
	print("The array has \(scores.count) elements.")
}

This code uses a wildcard to print the number of elements in the array for each loop iteration and array element.

Conclusion

This article has covered the most common features of arrays in Swift. Future articles will focus on even more advanced use cases.

Architecting SwiftUI apps with MVC and MVVM

It's easy to make an app by throwing some code together. But without best practices and robust architecture, you soon end up with unmanageable spaghetti code. In this guide I'll show you how to properly structure SwiftUI apps.

GET THE FREE BOOK NOW

Leave a Comment