Search⌘ K
AI Features

Swift Arrays

Explore how to work with arrays in Swift by learning array creation, mutable versus immutable arrays, accessing and modifying elements, iterating arrays, and managing mixed type collections using the Any type. This lesson equips you with the foundational skills to handle ordered data collections effectively in your Swift app projects.

Arrays and dictionaries in Swift are objects that contain collections of other objects. In this lesson, we will cover some of the basics of working with arrays and dictionaries in Swift.

Mutable and immutable collections

Collections in Swift come in mutable and immutable forms. The contents of immutable collection instances cannot be changed after the object has been initialized. To make a collection immutable, assign it to a constant when it is created using the let keyword. On the other hand, collections are mutable if assigned to a variable (using var).

Swift array initialization

An array is a data type designed specifically to hold multiple values in a single ordered collection. An array, for example, could be created to store a list of String values. Strictly speaking, a single Swift-based array is only able to store values that are of the same type. An array declared as containing String values, therefore, could not also contain an Int value. However, it is also possible to create mixed type arrays. This will BE demonstrated later in this chapter. The type of an array can be specified using type annotation or left to the compiler to identify using type inference.

An array may be initialized with a collection of values (referred to as an array literal) at creation time using the following syntax:

var variableName: [type] = [value 1, value2, value3, ……. ]

The following code creates a new array assigned to a variable (thereby making it mutable) that is initialized with three string values:

var treeArray = ["Pine", "Oak", "Yew"]

Alternatively, the same array could have been created immutably by assigning it to a constant:

let treeArray = ["Pine", "Oak", "Yew"]

In the above instances, the Swift compiler will use type inference to decide that the array contains values of String type and prevents values of other types from being inserted into the array elsewhere within the application code.

Alternatively, the same array could have been declared using type annotation:

var treeArray: [String] = ["Pine", "Oak", "Yew"]

Arrays do not have to have values assigned at creation time. The following syntax can be used to create an empty array:

var variableName = [type]()

Consider, for example, the following code which creates an empty array designated to store floating-point values and assigns it to a variable named priceArray:

var priceArray = [Float]()

Another useful initialization technique allows an array to be initialized to a certain size with each array element pre-set with a specified default value:

var nameArray = [String](repeating: "My String", count: 10) 

When compiled and executed, the above code will create a new 10 element array with each element initialized with a string that reads “My String.”

Finally, a new array may be created by adding together two existing arrays (assuming both arrays contain values of the same type). For example:

let firstArray = ["Red", "Green", "Blue"]
let secondArray = ["Indigo", "Violet"]
 
let thirdArray = firstArray + secondArray

Working with arrays in Swift

Once an array exists, you can use a wide range of methods and properties available in Swift to work with and manipulate the array content. The subset for this is as follows:

Array item count

A count of the items in an array can be obtained by accessing the array’s count property:

C++
var treeArray = ["Pine", "Oak", "Yew"]
var itemCount = treeArray.count
print("Item Count = \(itemCount)")

Whether or not an array is empty can be identified using the array’s Boolean isEmpty property as follows:

C++
var treeArray = [String]()
if treeArray.isEmpty {
print("Array is empty.")
} else {
print("Item Count = \(treeArray.count)")
}

Accessing array items

A specific item in an array may be accessed or modified by referencing the item’s position in the array index (where the first item in the array has index position 0) using a technique referred to as index subscripting. In the following code fragment, the string value contained at index position 2 in the array (in this case the string value “Yew”) is output by the print call:

C++
var treeArray = ["Pine", "Oak", "Yew"]
print(treeArray[2])

This approach can also be used to replace the value at an index location:

C++
var treeArray = ["Pine", "Oak", "Yew"]
print("Array item 1 = \(treeArray[1])")
treeArray[1] = "Redwood"
print("Array item 1 = \(treeArray[1])")

The above code replaces the current value at index position 1 with a new value that reads “Redwood.”

Array iteration

The easiest way to iterate through the items in an array is to make use of the for-in looping syntax. The following code, for example, iterates through all of the items in a String array and outputs each item to the console panel:

C++
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in treeArray {
print(tree)
}

The same result can be achieved by calling the forEach() array method. When this method is called on an array, it will iterate through each element and execute specified code. For example:

C++
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
treeArray.forEach { tree in
print(tree)
}

Note that since the task to be performed for each array element is declared in a closure expression, the above example may be modified as follows to take advantage of shorthand argument names:

C++
treeArray.forEach {
print($0)
}

Random items and shuffling

A call to the shuffled() method of an array object will return a new version of the array with the item ordering randomly shuffled. For example:

let shuffledTrees = treeArray.shuffled()

To access an array item at random, simply make a call to the randomElement() method:

C++
let treeArray: [String] = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
print("Random item = \(treeArray.randomElement()!)")
print("Random item = \(treeArray.randomElement()!)")
print("Random item = \(treeArray.randomElement()!)")

Appending items to an array

Items may be added to an array using either the append method or + and += operators. For example, the following are all valid techniques for appending items to an array:

C++
var treeArray = ["Pine", "Oak", "Yew"]
treeArray.append("Redwood")
treeArray += ["Myrtle"]
treeArray += ["Elm", "Maple", "Birch"]
for tree in treeArray {
print(tree)
}

Inserting and deleting array items

You can insert new items into an array by specifying the new item’s index location in a call to the array’s insert(at:) method. An insertion preserves all existing elements in the array, essentially moving them to the right to accommodate the newly inserted item:

C++
var treeArray = ["Pine", "Oak", "Yew"]
treeArray.insert("Maple", at: 0)
for tree in treeArray {
print(tree)
}

Similarly, an item at a specific array index position may be removed using the remove(at:) method call:

C++
var treeArray = ["Pine", "Oak", "Yew"]
treeArray.remove(at: 2)
for tree in treeArray {
print(tree)
}

To remove the last item in an array, simply make a call to the array’s removeLast() method as follows:

C++
var treeArray = ["Pine", "Oak", "Yew"]
treeArray.removeLast()
for tree in treeArray {
print(tree)
}

Creating mixed type arrays

A mixed type array is an array that can contain elements of different class types. Clearly, an array that is either declared or inferred as being of type String cannot subsequently be used to contain non-String class object instances. Interesting possibilities arise, however, when taking into consideration that Swift includes the Any type. Any is a special type in Swift that can be used to reference an object of a non-specific class type. Therefore, an array declared as containing Any object types can be used to store elements of mixed types. For example, the following code declares and initializes an array containing a mixture of String, Int and Double elements:

let mixedArray: [Any] = ["A String", 432, 34.989]

The use of the Any type should be used with care since the use of Any hides the true type of the elements from Swift. In such an array as that, it leaves code prone to potential programmer error. It will often be necessary, for example, to manually cast the elements in an Any array to the correct type before working with them in code. Performing the incorrect cast for a specific element in the array will most likely cause the code to compile without error but crash at runtime. For the sake of an example, consider the following mixed type array:

let mixedArray: [Any] = [1, 2, 45, "Hello"]

Having initialized the array, assume that we now need to iterate through the integer elements in the array and multiply them by 10. The code to achieve this might read as follows:

C++
let mixedArray: [Any] = ["A String", 432, 34.989]
for object in mixedArray {
print(object * 10)
}

When compiled, however, the above code triggers a syntax error indicating that it is not possible to multiply operands of type Any and Int.

error: cannot convert value of type 'Any' to expected argument type 'Int'

In order to remove this error, it will be necessary to downcast the array element to be of type Int:

C++
let mixedArray: [Any] = ["A String", 432, 34.989]
for object in mixedArray {
print(object as! Int * 10)
}

The above code will compile without error. It will work as expected until the first non-String element in the array is reached, at which point the code will crash with the following error:

Could not cast value of type 'Swift.String' (0x7fbc071fca58) to 'Swift.Int' (0x7fbc071fe688).

The code will, therefore, need to be modified to be aware of the specific type of each element in the array. Clearly, there are both benefits and risks to using Any arrays in Swift.

Lesson recap

  • Arrays hold multiple values in a single ordered collection.

  • When assigned to a constant, an array is immutable.

  • When assigned to a variable, an array is mutable.

  • An array may either be declared as initially empty or pre-initialized with a set of existing elements called an array literal.

  • A range of properties and methods may be used to obtain information about any array and access, add, shuffle and delete elements.

  • Mixed type arrays may be declared by specifying Any as the element type. This is a technique which should be used with caution.

Quiz

Use this quiz to test your understanding of Swift arrays.

Technical Quiz
1.

Which statement will access the element containing the “Red” string value in the following array?

var colorArray = ["Blue", "Green", "Red", "Yellow"]
A.
let redColor = colorArray[3]
B.
let redColor = colorArray.itemAt(3)
C.
let redColor = colorArray[2]
D.
let redColor = colorArray(2)

1 / 3

Exercises

Practice your knowledge of Swift arrays by completing these exercises.

Exercise 1

Write code to iterate through and display each of the elements in the following array:

Exercise
Solution
let myArray = [1, 4, 6, 12, 5, 3, 6]

Exercise 2

Add code to remove the final item in the following array:

Exercise
Solution
var myArray = ["Kia", "Ford", "Audi", "Toyota", "BMW", "Tesla"]
for item in myArray {
print(item)
}

Exercise 3

Create an array of 20 elements all containing the number 10.

Exercise
Solution
let myArray =