The Guide to Swift Arrays

During your programming adventures you might have stumbled upon the term Array a couple of times.  What is it and why is it important? To put it simply an Array is a collection of elements that is in an ordered series or arrangement. It is important because it organizes and compiles data so that it …

Continue Reading…

Written by

Chris C

Published on

29 Aug 2019

During your programming adventures you might have stumbled upon the term Array a couple of times. 

What is it and why is it important? To put it simply an Array is a collection of elements that is in an ordered series or arrangement.

It is important because it organizes and compiles data so that it can be easily managed and accessed. To better understand Arrays it is best to go back to the basics.

The basics

Suppose that we have to store data of 5 random samples of a product rating, in our normal way to do things we would probably go about by making 5 separate variables named rating1, rating2, rating3, etc.

var rating1 = 95
var rating2 = 87
var rating3 = 92
var rating4 = 99
var rating5 = 84 

This is clearly correct but isn’t it a bit cluttered? It also needs to have all 5 variables declared and may be hard to track in the future.

This is where Arrays come in, instead of the mess above we can simply write it as such:

var rating = [95, 87, 92, 99, 84]

Wasn’t that a lot easier and cleaner? There is a catch though, Array values can be extracted using indexes, and these indexes always start with 0 and not the usual 1.

<pre><code class="swift">rating[0] // has the value 95
rating[1] // has the value 87
rating[2] // has the value 92
rating[3] // has the value 99
rating[4] // has the value 84</code></pre>

A minor sacrifice if you ask me. How about we try printing our data? To do so just write it as

print(rating[0]) // prints 95
print(rating[1]) // prints 87
print(rating[2]) // prints 92
print(rating[3]) // prints 99
print(rating[4]) // prints 84
print(rating) // prints [95, 87, 92, 99, 84]

Following the same logic we can then treat our array as if its a normal Int variable like so

rating[0] = 78 //assigns a new value to the specified index
rating[0] = 17 + 15 + 20 + 18 + 17 //treat it as such as long as it will result in an Int

Of course like any other variable our array can also handle all data types but just remember that once you assign a data type to it then you should use it all throughout

var colors = [“red”, “green”, “blue”]
colors[0] = “bright red”

It is also worth to note that we can also declare an empty array that can be done like so

// short form easier to read
var emptyNumbers: [Int] = []

// can be typed in full form
var emptyNumbers: Array[Int] = Array()

Useful built-in functionalities

Checking and determining number of content

You can check if an array has no values by using isEmpty. Additionally, you can also check the number of content it has by using count

var colors = [“red”, “green”, “blue”]
	If colors.isEmpty{
		print(“I don’t know any colors.”)
} else {
print(“I know \(colors,count) colors.”) //prints I know 3 colors.
}

Accessing First and Last content of the array

You can check the first value of the array by using first. Conversely, you can also check the last value of the array by using last.

var rating = [95, 87, 92, 99, 84]

print(rating.first) //prints 95
print(rating.last) //prints 84

Subscript/Slice of the array

You can get a subscript/slice of an array by using the Range operator ()

var rating = [95, 87, 92, 99, 84]

print(rating[0...2]) //prints [95, 87, 92]
print(rating[1...4] //prints [87, 92, 99, 84]

Adding and Removing elements to the array

Basic functionalities

You can add elements to the array by using append or insert([value], at: [index]). Conversely, you can also remove elements to the array by using remove(at: [index]).

var rating = [95, 87, 92, 99, 84]

rating.append(91) // rating is now  [95, 87, 92, 99, 84, 91]

rating.insert(100, at: 2) // rating is now  [95, 87, 100, 92, 99, 84, 91]

rating.remove(at: 3) //rating is now  [95, 87, 100, 99, 84, 91]

Advanced functionalities

What is interesting to note is that different combinations that you can add and remove data these are
insert(contentsOf:[array], at: [index]) – Instead of just inserting a single value at a specified index we can insert a whole array or range of values inside as well.

var colors = ["red", "green", "blue"]

colors.insert(contentsOf: ["yellow","orange"], at: 1)

print(colors) //prints ["red", "yellow", "orange", "green", "blue"]

replaceSubrange([range from own array], with: [array] – We can also replace a whole range of values with another one.

var rating = [95, 87, 92, 99, 84]

rating.replaceSubrange(1...3, with: [100,90])

print(rating) //prints [95, 100, 90, 84]

append(contentsOf: [array]) – We can also add a range of values at the end of an array using

var rating = [95, 87, 92, 99, 84]

rating.append(contentsOf: [100, 90])

print(rating) //prints [95, 87, 92, 99, 84, 100, 90]

removeFirst() – is to remove the first value of the array 

removeFirst([num]) – is to remove the first [num] of values from the array

var rating = [95, 87, 92, 99, 84]

rating.removeFirst()

print(rating) //prints [87, 92, 99, 84]

rating.removeFirst[2]

print(rating) //prints [99, 84]

Conversely you can also use

removeLast() – is to remove the last value of the array  

removeLast([num]) – is to remove the last [num] of values from the array

var rating = [95, 87, 92, 99, 84]

rating.removeLast()

print(rating) //prints [95, 87, 92, 99]

rating.removeLast[2]

print(rating) //prints [95, 87]

removeSubrange([range]) – is to remove elements in a specified range

var rating = [95, 87, 92, 99, 84]

rating.removeSubrange(1...3)

print(rating) //prints [95, 84]

Checking for data inside the array

contains([element]) – is to check if the element/value is inside the array, returns a Bool

It can also be written as contains(where: [element])

var rating = [95, 87, 92, 99, 84]

rating.contains(99) //returns true
rating.contains(where: 90) //returns false

min() – is to get the lowest value in the array. Note that if you compare strings it will get and compare the ASCII value of the letter/string

var rating = [95, 87, 92, 99, 84]
print(rating.min()) //prints 84

var letters = [“a”, “b”, “A”]
print(letters.min()) //prints A

To check more into ASCII values you can check out this website http://www.asciitable.com/. In our case “A” is min because it has an ASCII value of 65, compared to a and b that has an ASCII value of 97 and 98 respectively.

max() – is to get the highest value in the array. Note that if you compare strings it will get and compare the ASCII value of the letter/string

var rating = [95, 87, 92, 99, 84]
print(rating.max()) //prints 99

var letters = [“a”, “b”, “A”]
print(letters.max()) //prints b

Miscellaneous uses for data inside the array

sort() – sorts the value of the array. Note that if you compare strings it will get and compare the ASCII value of the letter/string

You can also apply sort in descending using sort(by: > )

var rating = [95, 87, 92, 99, 84]
	rating.sort()
print(rating) //prints [84, 87, 92, 95, 99]

	rating.sort(by: >)
print(rating) //prints [99, 95, 92, 87, 84]


var letters = [“a”, “b”, “A”]
letters.sort()
print(letters) //prints [“A”, “a”, “b”]

reverse() – it reverses the data inside the array

var rating = [95, 87, 92, 99, 84]
rating.reverse()
print(rating) //prints [84, 99, 92, 87, 95]

shuffle() – it shuffles the values of the array in a random order

var rating = [95, 87, 92, 99, 84]
rating.shuffle()
print(rating) //prints [92, 95, 87, 99, 84]

randomElement() – it takes a random element in the array

var rating = [95, 87, 92, 99, 84]
print(rating,randomElement()) //prints 99

forEach{ [element] -> Void } – iterates over the array and does specified commands to it

var rating = [95, 87, 92, 99, 84]

rating.forEach{ num in 
print(num) 
} //prints the values of rating from 0 - 4

This can be written in another way by utilizing loops

for num in rating {
print(num)
} //prints the values from 0 - 4, same as above

And that’s it! Hope this information will serve you well to better understand and utilize Arrays in the future 🙂

Table of contents
    5 Shares
    Share
    Tweet
    Pin
    Share
    Buffer