Swift Arrays

What is a Swift Array and How to create?

Tested on: Xcode 12.2, Swift 5.3

The array is a common collection type in Swift which you can store multiple values or data in a variable or constant. The values that are stored in the array are in order. The value inside the array is also known as an element. For example, the first element is the array shown below is 10 and the second element is 20 and so on.


Swift Array indexing

When should you use arrays?

Before you decide on an array, you should consider the reason for using them. Arrays are useful when you are to store item in a particular order which you may sort them in a certain order or get the element by its order.

For example, you can store the score of the students [5, 8, 20, 50, 55, 60, 70] in increasing number and get the first value out by calling it index.

To futher your understanding, you will learn

  1. How to create an Array in Swift?
  2. How to access and indexing an Array?
  3. How to modify an array? (Adding, Removing and Updating)
  4. How to slice an Array?
  5. Array methods and properties





1. How to create an Array?

You can create an array by using Array literal and to create an array literal you can use square brackets and inside the square brackets it contains the value and each value are separate by a comma.

Swift Code :

let oddNumbers = [1, 3, 5, 7, 9]

As you know, Swift able to infers the type of the variable or constant and it infers oddNumbers to be an array of Int and it is written as [ Int ]. The square brackets define it as an array and its data type is inside which is Int. However, you can also explicitly state it data type as shown below:

Swift Code :

let oddNumbers:[Int] = [1, 3, 5, 7, 9]

Swift doesn't allow you to store value with different data type. An error will occur if you do that.

Swift Code :

let mixDate = [1, "3", 5, "7", 9]

Output :

error: heterogeneous collection literal could only be inferred to '[Any]'


Tips: Storing different data type in an Array by making the type explicit

However, like what the error message show, you can explicitly state the data type to [Any].

Swift Code :

let mixDate:[Any] = [1, "3", 5, "7", 9]



2. How to access and indexing an Array?

Before you start to access the value in the array, you have to know how they are indexed or counted.

Zero-index

Elements in the array are zero-indexed meaning that the first element is zero and not one as shown in the image below. There are five elements in the array.

Swift Array indexing

Accessing the element

The most common and convenient way to access the elements in the array is using subscript. Subscript allows you to access any value by stating the index of the element inside square brackets.

Swift Code :

let oddNumbers:[Int] = [1, 3, 5, 7, 9]
print(oddNumbers[1])

Output :

3




3. How to modify the array?

You can make changes to arrays as arrays are mutable. The changes that you can make to an array include updating existing value, adding and removing.

3.1 Updating the value in the array

You can change the value of the element by using square braket to access the value and using equal (=) operator to assign a new value to it.

Swift Code :

var currentQueue = ["Wes", "Eric", "Evan"]
currentQueue[1] = "Jes"
print(currentQueue)

Output :

["Wes", "Jes", "Evan"]


3.2 Adding an element to an array

You can add an element to an array using append, + (add), and Insert method.

Append Method - append method is used to add an element to the back of an array. For example, if a new customer, Jean wants to join a queue to purchase an item, you can add her to the back of the queue using append.

Swift Code :

var currentQueue = ["Wes", "Jes", "Evan"]
currentQueue.append("Jean")
print(currentQueue)

Output :

["Wes", "Jes", "Evan", "Jean"]


+ Operator - you can also add them to the back using add operator to an array. This works the same as the append method.

Swift Code :

var currentQueue = ["Wes", "Jes", "Evan"]
currentQueue += ["Jean"]
print(currentQueue)

Output :

["Wes", "Jes", "Evan", "Jean"]


Insert Method - insert method is used to add an element to the index you want by using insert(Element, at: index). For example, Alex asked his friend to help him to queue and once, Alex arrived. He will queue in front of his friend, Joe.

Swift Code :

var currentQueue = ["Wes", "Joe", "Jes", "Evan"]
currentQueue.insert("Alex", at: 1)
print(currentQueue)

Output :

["Wes", "Alex", "Joe", "Jes", "Evan"]


3.3 Removing an element in an array

You can remove an element by using two method removeLast() and remove(at: ).

removeLast method - as the name implied. You can remove the last element by using removeLast method. For example, Evan is frustrated as the queue is long and so, he wants to leave the queue and he is the last person in the queue. Thus, you can use removeLast.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes", "Evan"]
currentQueue.removeLast()
print(currentQueue)

Output :

["Wes", "Alex", "Joe", "Jes"]


remove(at: ) method - you can state the index of the element you want to remove by using remove(at: index). For example, the queue is long and Joe got to go and he is at index 2. You can remove him by stating the index.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
currentQueue.remove(at: 2)
print(currentQueue)

Output :

["Wes", "Alex", "Jes"]

What if you do not know the index of the element? There is a method in Swift that allows you to find the element of the index using firstIndex(of: ) and this method returns the firstIndex of the element. This is because array allows you to store multiple copies of the same value and this method finds the first value of it. It will return nil, if it can find anything.




4. How to slice an Array?

Sometimes you want to access more than a single value from an array. A faster way of doing it is to use Array Slicing. Which you use square brackets and countable ranges.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue[1...3])

Output :

["Alex", "Joe", "Jes"]




5. Arrays Method and properties?

.count

.count is an array's property and it counts the number of elements in the array. Do not confuse with indexing because when counting the number of elements in an array. The counting start from one and not zero. For example, the size of the element in the array in currentQueue is 4 while the last index is 3.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.count)

Output :

4


.isEmpty

.isEmpty is An array's property and it checks whether the array is empty or not. It returns true, if it is empty and false when it is not.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.isEmpty)

Output :

false


.first

.first is an array's property and fetch the first element of an array. It returns an optional because if the array is empty, it will return nil instead.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.first)

Output :

Optional("Wes")


.last

.last is an array's property and it is opposite to .first. It fetches the last element of an array.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.last)

Output :

Optional("Jes")


.min()

.min() return the lowest values in the array and not the lowest index. If the value is a string like the one below it will return the lowest alphabetical order.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.min())

Output :

Optional("Alex")


.max()

.max() return the highest values in the array and not the highest index. If the value is a string like the one below it will return the highest alphabetical order.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.min())

Output :

Optional("Wes")


.contains()

.contains(value) allows you to check if there is an specific value inside the array. .contains take in an property called value and it is the value you want to find. For example, I want to check if "Alan" is inside the currentQueue.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
print(currentQueue.contains("Alan"))

Output :

false


.sort() and sorted()

.sort and sorted allows you to sort the array in a certain order you can state the way you want to sort by adding the "by" parameter. The difference between sort and sorted is that sorted leave the original array untouched and return a copy.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
currentQueue.sort()
print(currentQueue)

Output :

["Alex", "Jes", "Joe", "Wes"]


Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
currentQueue.sort(by: >)
print(currentQueue)

Output :

["Wes", "Joe", "Jes", "Alex"]


.swapAt(index, index)

.swapAt method allows you to swap two positions of an element.

Swift Code :

var currentQueue = ["Wes", "Alex", "Joe", "Jes"]
currentQueue.swapAt(0, 2 )
print(currentQueue)

Output :

["Joe", "Alex", "Wes", "Jes"]


.reserveCapacity(Int)

.reserveCapacity can be used to increase the performance if you know how much data, the array will be storing. .reserveCapacity(Int) take in a parameter which is an Int and it indicated the size of the array.

The reason to add this is because newly allocated storage might be greater than the requested capacity if Swift determines the size by itself. By stating it, you tell Swift the size of the minimum capacity and Swift will not allocate more space for it. Therefore, avoiding over allocation.

Swift Code :

currentQueue.reserveCapacity(5)

Output :

false