Swift arrays are a very common data type used to organize your app’s data.
You can store multiple elements into an array, such as integers or strings.
For example, here is an array of numbers:
let numbers = [1, 2, 3, 4, 5]
With arrays, you can do a lot of useful tasks, such as add, remove, or update the elements. You can also neatly loop through the arrays element by element.
In this guide, you learn how to work with arrays in Swift.
This chapter is part of a completely free Swift for Beginners guide. Make sure you have completed all the chapters from the start before reading this one.
Disclaimer: To learn Swift, you have to repeat everything you see in this guide and in the following guides. If you only read the guides, you are not going to learn anything!
Arrays in Swift
In Swift, an array is a data type, or rather, a data structure where you can store multiple items.
For example, an array can store the daily temperatures of a week, the students of a course, the users of an app, and so on.
There are many use cases for arrays in Swift.
As a matter of fact, you are going to use arrays in each and every application you ever write.
Thus, you should make sure you know the basics of arrays and how to use them.
How to Create an Array
To create an array in Swift place comma-separated values inside a set of square brackets.
Here is the general syntax:
[elem1, elem2, elem3, ... ,elemN]
Where elem1, elem2, elemN are the elements stored inside an array.
These elements can be anything, as long as they are of the same data type.
Also, there can be as many elements as you need.
For instance, let’s create an array of integers:
let numbers = [1, 2, 3, 4, 5]
What Is the Data Type of an Array?
In Swift, an array is a data type just like a string, integer, or boolean.
As you have learned, a string is represented with String, an integer with Int, and a boolean with Bool.
But how do you denote an array?
An array is denoted with []. In addition to this, you need to specify the data type of the array elements inside the square brackets.
For instance, an array of integers is of type [Int].
var numbers: [Int] = [1, 2, 3, 4, 5]
The data type [Int] tells Swift that the array is going to store integers.
If you try to store something else in this array, you are going to see an error.
Specifying the explicit data type is mandatory when you create an empty array. This makes sense, as Swift needs to know what elements it should expect later on.
For example, let’s create an empty array of Strings:
var numbers: [String] = []
Next, let’s talk about accessing array elements with an index.
Array Indexing Explained
In Swift, you can access array elements with an index.
But unlike you thought, the indexing does not start from 1.
It starts from 0.
In other words:
- The 1st element has an index of 0.
- The 2nd element has an index of 1.
- The 3rd element has an index of 2.
And so on.
This is one of those things you are going to get wrong countless times as a beginner.
Now that you know how array elements are indexed, you are ready to learn how to access them.
How to Access an Element of an Array
To access array elements in Swift, use the square brackets operator [] by passing it the index of the element you want to access.
array[index]
For example, let’s access the 1st and the 2nd element of an array:
var names = ["Alice", "Bob", "Charlie", "David"] let first: String = names[0] let second: String = names[1] print(first, second)
Output:
Alice Bob
As you can see, index 0 returned the 1st element. Likewise, index 1 returned the 2nd element.
An array is a data type that comes with a bunch of useful built-in methods.
For example, these methods can be used to add or remove elements from an array.
Next, let’s discuss how to add new elements to an array.
How to Add an Element to an Array
In Swift, you can add a new element to the end (right-hand side) of an array using the built-in append() method.
array.append(elem)
For example, let’s create an array of integers. Then on the next line, let’s add an integer to the end of it:
var numbers = [1, 2, 3, 4, 5] numbers.append(6) print(numbers)
Next, let’s talk about updating array elements.
How to Update an Element in an Array
To update an array element in Swift, you need to access the element with the index and then update its value.
array[index] = newValue
For example, let’s create an array of integers. Then let’s modify the first integer of the array
var numbers = [1, 2, 3, 4, 5] numbers[0] = 1000 prin(numbers)
Output:
[1000, 2, 3, 4, 5]
As you can see, this updated the first element of the original array from 1 to 1000.
Next, let’s see how to remove array elements in Swift.
How to Remove an Element from an Array
To remove array elements in Swift, you need to know the index of the element to be removed. Then you need to call the built-in remove() method.
array.remove(at: index)
For instance, let’s create an array of strings. Then let’s remove the 2nd element (at index 1):
var names = ["Alice", "Bob", "Charlie", "David"] names.remove(at:1) print(names)
Output:
["Alice", "Charlie", "David"]
This removed the name “Bob” from the original array.
So far you have learned the basic operations on the array, that is, how to:
- Create an array.
- Add an element to an array.
- Update an array element.
- Remove an array element.
To complete this guide, you need to learn one more thing.
This is of course how to loop through an array element-by-element.
How to Loop Through an Array
In Swift, an array can store multiple elements in the same data structure.
Sometimes, there can be thousands and thousands of elements in an array.
What if you wanted to perform some action on each element in the array?
In this case, it would make absolutely no sense to manually go through these elements.
Instead, you can loop through the elements.
You can use either a for loop or a while loop.
For Loop Syntax with Arrays
With for loops, the syntax looks like this:
for element in array { // actions }
This code construct loops through the array element by element, such that:
- Each item in the array is assigned to a temporary constant called element.
- The element constant can be accessed only inside the loop.
While Loop Syntax with Arrays
To use a while loop to iterate over an array, you need to know the number of array elements and keep track of the number of iterations.
Here is how a while loop generally looks when used to iterate over an array:
var i = 0 while i < array.count { // actions // increment i }
This loop continues as long as the looping parameter i is less than the number of elements in the array. And as you learned in the while loops chapter, you should always update the looping condition inside the loop. In this case, you need to increment the looping variable i.
Now let’s see some examples to make some sense of these.
Loop Examples
For instance, let’s create an array of names and use a for loop to print each name out:
var names = ["Alice", "Bob", "Charlie", "David"] for name in names { print(name) }
Output:
Alice Bob Charlie David
To demonstrate while loops, let’s repeat the same example with a while loop:
var names = ["Alice", "Bob", "Charlie", "David"] var i = 0 while i < names.count { print(names[i]) i += 1 }
Output:
Alice Bob Charlie David
To choose between a for loop and a while loop is up to you.
However, it is generally advisable to use for loop whenever possible. If you cannot get the job done with a for loop, use a while loop.
Let’s see a bunch of useful and demonstrative examples of arrays and loops in Swift.
Examples of Arrays in Swift
So far you have seen some basic examples of how to use arrays in Swift.
However, let’s take a look at a bunch of useful and slightly more advanced examples.
Example 1: Square Each Number in an Array
To square each number in an array in Swift, you need to use a while loop:
- Start a looping index i at 0.
- Loop until the index equals the length of the array.
- For each iteration, multiply the ith element by itself and assign it to the original value.
Here is how it looks in code:
var numbers = [1, 2, 3, 4, 5] var i = 0 while i < numbers.count { numbers[i] = numbers[i] * numbers[i] i += 1 } print(numbers)
As a result, you get the numbers squared:
[1, 4, 9, 16, 25]
This is a great example of a task that can be accomplished with a while loop but not with a for loop.
But why no for loop?
As mentioned earlier, the for loop assigns each array element to a constant.
This constant is a copy of the original array element. Furthermore, because it is a constant you cannot modify it.
Let’s give it a try and see what happens:
var numbers = [1, 2, 3, 4, 5] for number in numbers { number = number * number } print(numbers)
This results in an error:
error: cannot assign to value: 'number' is a 'let' constant
Example 2: Filter Even Numbers
Given an array of numbers, let’s filter even numbers.
In other words, let’s remove all the odd numbers from the mix.
To filter out all the odd numbers, you need to follow these steps:
- Start a loop index i at 0, that is, the beginning of the array.
- Loop as long as the index is less than the number of elements in the array.
- Check if the ith number is odd. If it is, remove the ith element from the original array.
- Update the index i at the end of each iteration.
Here is how it looks in code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] var i = 0 while i < numbers.count { let num = numbers[i] if num % 2 != 0 { numbers.remove(at: i) } i += 1 } print(numbers)
Output:
[2, 4, 6, 8, 10]
Example 3: Array of Custom Objects
So far you have seen arrays that consist of elementary data types such as integers and strings.
However, you can store any other type in an array in Swift.
This can be your own custom data type as well.
For example, let’s write a Student struct and add Student objects to an array. Furthermore, let’s loop through the array and print the name of each student.
Here is how it looks in code:
struct Student { var name: String var gpa: Double } var stud1 = Student(name: "Alice", gpa: 4.3) var stud2 = Student(name: "Bob", gpa: 2.9) var stud3 = Student(name: "Charlie", gpa: 3.4) let students: [Student] = [stud1, stud2, stud3] for student in students { print(student.name) }
Output:
Alice Bob Charlie
This completes the chapter on arrays in Swift.
In the next chapter, you are going to learn another really common data type called Dictionary.
Next chapter: Dictionaries in Swift
Conclusion
Today you learned how to use arrays in Swift.
To recap, an array data type is used to store multiple elements in the same place.
You can create an array by adding comma-separated elements inside a set of square brackets.
var arr = [elem1, elem2, ... , elemN]
The data type of an array is denoted with [] by passing the data type of the elements inside of the square brackets.
For example, the data type of an array of strings is [String].
var names: [String] = ["Alice", "Bob", "Charlie", "David"]
With arrays you can easily:
- Access elements.
- Add new elements.
- Modify elements.
- Remove elements.
- Loop through the elements.
Here is a quick recap of these operations:
// #1 Access ith element arr[i] // #2 Add new element arr.append(elem) // #3 Modify the ith element arr[i] = newValue // #4 Remove the ith element arr.remove(at: i) // #5 Loop through an array for element in arr { // actions }
Next chapter: Dictionaries in Swift
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)
JavaScript2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)