Chapter 6: Arrays

An array is a collection type. It stores collections of data of multiple types and orders them numerically.


What you will learn

  • Creating your first Array
  • Appending an item To an Array
  • Removing an item From an Array
  • Creating an empty Array
  • Other Neat things Arrays can do

Key Terms

  • Zero-indexing: a term to describe the starting point (0) at which a Swift Array begins counting.
  • Array: a collection type in Swift where values are collected and ordered numerically.
  • Append: to add a value to an array.
  • Empty Array: an array with no values stored inside – how sad. 😭

The variables we learned about in chapter 3 are great for storing single values. In the real world, we need to keep track of multiple pieces of data that are all a part of the same category. For example – employee salaries, the value of each comic book in our collection, or the cost per item in a store inventory.

It is time and labor-intensive to create an individual variable for each of the above items and honestly it wouldn't be good code. This is where arrays come in cue triumphant music!

Arrays are a collection of values that allow us to store multiple values. In this chapter, we will see just how useful they can be.

Setting up a Playground

First, open Xcode if you haven't already and click Create New Playground. Give it a name like Arrays and click Next. Choose somewhere to save this .playground file and click Create to save it. You should see a screen like the one in Figure 1.6.1.

Figure 1.6.1 Screen Shot 2016-10-10 at 5.01.11 AM.png

Delete all the boilerplate code on the left side but leave import UIKit as it is necessary.

Creating your first array

Let's use one of the above examples: the value of each comic book in our collection. 🤓 Imagine that you have a collection, albeit a small one, that includes 5 comic books. They each have differing values. We could create a variable for each comic book and store the value like so:

var comicBook1 = 10.0
var comicBook2 = 27.50
var comicBook3 = 1015.0
var comicBook4 = 55.0
var comicBook5 = 2.0

What if someone stole on of your comic books? What if you sold one? You would need to manually remove that line of code and then re-number the variables that follow it because each variable has a specific number and order.

Instead, create an Array called comicBooks and place the values inside of it like so:

var comicBooks = [10.0, 27.50, 1015.0, 55.0, 2.0]

Now we have a single line of code to replace the five lines we wrote above. We've written an array of type Int and have filled the braces ([]) with data.

Appending an item to an array

When we foolishly wrote the 5 variables above, it was difficult to manage and change. If we wanted to add a new comic book, we would have to add it at the end otherwise we would have messed up the number order of each variable. With an array, it is easy to manage and modify our data.

For instance, let's pretend that you scored and found an ultra-rare comic book at a garage sale. After researching, you learn that it's value is $500.

To add is to our array, simply type:

var comicBooks = [10.0, 27.50, 1015.0, 55.0, 2.0]

comicBooks.append(500.0)

On the right-hand side of the Playground window, you should see the array print out, this time with a new value at the end – 500.0!

Other things arrays can do

Arrays can do a couple cool things to help us manage a collection of data. For instance, we can calculate the total number of objects in our array. Just for explanation purposes, we are going to print the number of items in our array before we added our new $500 comic and after, too.

Try this:

var comicBooks = [10.0, 27.50, 1015.0, 55.0, 2.0]

print(comicBooks.count) // Prints 5 because of total above.

comicBooks.append(500.0)

print(comicBooks.count) // Prints 6 because we added a new value!

Pretty cool! What if you sold one of your comic books on eBay? How would we remove that item from the array?

Removing an item from an array

Arrays in Swift include a function called .remove(at:) which allow us to remove a certain item at a certain point in our array.

To remove the third value from our array, we need to add the following line of code:

var comicBooks = [10.0, 27.50, 1015.0, 55.0, 2.0]
print(comicBooks.count) // Prints 5 because of total above.

comicBooks.append(500.0)
print(comicBooks.count) // Prints 6 because we added a new value!

comicBooks.remove(at: 2)

Wait a minute... Didn't I just say to remove the third value from our array? Yes, and that is exactly what I did. You should see the third value (1015.0) printed out on the right-hand side of the Playground. So it worked, but if this is confusing it's okay because this is where I will talk about zero-indexing.

In most programming languages, arrays use what is called zero-indexing meaning that the first value in our array is given an identifier of 0 to indicate the first value. The second value has the identifier (or index) of 1, and so on. If you want the fourth value, you need to ask Swift for an index of 3. It may seem confusing, but that's just the way it is.

In the above code, we wanted to remove the third comic book from our array, so we asked to remove the item at index 2.

If we print comicBooks.count below comicBooks.remove(at: 2) you should see that the count is back down to 5.

...
comicBooks.remove(at: 2)

print(comicBooks.count) // Prints 5

Creating an empty array

Let's move on to another example – students in a classroom. Type the following beneath all the code you wrote above:

var students = [String]()

The above code is an empty array. We have declared a variable called students and have asked Xcode to make it an empty array containing String values. In regards to an array, "empty" means that it doesn't yet have any values – like an empty box or container would be with nothing inside.

To show that there is nothing inside, add the following:

var students = [String]()

print(students.count) // Prints 0 because our array is empty!

Now we can add students to our Array! Use the .append() function to do so:

var students = [String]()

print(students.count) // Prints 0 because our array is empty!

students.append("Jon")
students.append("Jacob")
students.append("Jose")
students.append("Jingle")
students.append("Heimer")
students.append("Schmidt")

In your Playground window, you should see the following (Figure 1.6.2):

Figure 1.6.2 Screen Shot 2016-10-20 at 5.34.03 AM.png

The pyramid-like print out of values on the right-hand side shows how each time we run .append() to add a value, the Array becomes longer and includes more values.

Wrapping up

There are many more cool things that arrays can do, but you have learned the essentials in this chapter. Arrays are collection type and as such, they are great for storing collections of values. Whatever you have a list of – teachers, hot wheel cars, Minecraft collectibles, you name it – arrays are a great way to store that data.

We are starting to get better at organizing and writing cleaner code and will continue to do so throughout this book. Nicely done on getting this far! You deserve a cookie! 🍪

Exercise

Create an Array called favoriteAlbums and fill it with the titles of four albums that you love. (Hint: They should all be values of type String). Add a new album title to your array by using the .append() feature in Swift. Print the total count of the items in the array using .count.

I'm going to make you be picky now... Use Swift's remove(at:_) feature to remove an album from your array.