Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Toy Bin

Save for later
  • 8 min read
  • 08 Mar 2017

article-image

In this article by Steffen Damtoft Sommer and Jim Campagno, the author of the book Swift 3 Programming for Kids, we will walk you through what an array is. These are considered collection types in Swift and are very powerful.

(For more resources related to this topic, see here.)

Array

An array stores values of the same type in an ordered list. The following is an example of an array:

let list = ["Legos", "Dungeons and Dragons", "Gameboy", "Monopoly", "Rubix
Cube"]

This is an array (which you can think of as a list). Arrays are an ordered collections of values.

We've created a constant called list of the [String] type and assigned it a value that represents our list of toys that we want to take with us. When describing arrays, you surround the type of the values that are being stored in the array by square brackets, [String]. Following is another array called numbers which contains four values being 5, 2, 9 and 22:

let numbers = [5, 2, 9, 22]

You would describe numbers as being an array which contains Int values which can be written as [Int]. We can confirm this by holding Alt and selecting the numbers constant to see what its type is in a playground file:

toy-bin-img-0

What if we were to go back and confirm that list is an array of String values. Let's Alt click that constant to make sure:

toy-bin-img-1

Similar to how we created instances of String and Int without providing any type information, we're doing the same thing here when we create list and numbers. Both list and numbers are created taking advantage of type inference. In creating our two arrays, we weren't explicit in providing any type information, we just created the array and Swift was able to figure out the type of the array for us.

If we want to, though, we can provide type information, as follows:

let colors: [String] = ["Red", "Orange", "Yellow"]

colors is a constant of the [String] type.

Now that we know how to create an array in swift, which can be compared to a list in real life, how can we actually use it? Can we access various items from the array? If so, how? Also, can we add new items to the list in case we forgot to include any items? Yes to all of these questions.

Every element (or item) in an array is indexed. What does that mean? Well, you can think of being indexed as being numbered. Except that there's one big difference between how we humans number things and how arrays number things. Humans start from 1 when they create a list (just like we did when we created our preceding list). An array starts from 0. So, the first element in an array is considered to be at index 0: 

toy-bin-img-2

Always remember that the first item in any array begins at 0.

If we want to grab the first item from an array, we will do so as shown using what is referred to as subscript syntax:

toy-bin-img-3

That 0 enclosed in two square brackets is what is known as subscript syntax. We are looking to access a certain element in the array at a certain index. In order to do that, we need to use subscript index, including the index of the item we want within square brackets. In doing so, it will return the value at the index. The value at the index in our preceding example is Legos. The = sign is also referred to as the assignment operator. So, we are assigning the Legos value to a new constant, called firstItem.

If we were to print out firstItem, Legos should print to the console:

print(firstItem)
// Prints "Legos"

If we want to grab the last item in this array, how do we do it?

Well, there are five items in the array, so the last item should be at index 5, right? Wrong!

What if we wrote the following code (which would be incorrect!):

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at £16.99/month. Cancel anytime
let lastItem = list[5]

This would crash our application, which would be bad. When working with arrays, you need to ensure that you don't attempt to grab an item at a certain index which doesn't exist. There is no item in our array at index 5, which would make our application crash. When you run your app, you will receive the fatal error: Index out of range error.

This is shown in the screenshot below:

toy-bin-img-4

Let's correctly grab the last item in the array:

let lastItem = list[4]
print("I'm not as good as my sister, but I love solving the (lastItem)")
// Prints "I'm not as good as my sister, but I love solving the Rubix Cube"

Comments in code are made by writing text after //. None of this text will be considered code and will not be executed; it's a way for you to leave notes in your code.

All of a sudden, you've now decided that you don't want to take the rubix cube as it's too difficult to play with. You were never able to solve it on Earth, so you start wondering why bringing it to the moon would help solve that problem. Bringing crayons is a much better idea.

Let's swap out the rubix cube for crayons, but how do we do that?

Using subscript syntax, we should be able to assign a new value to the array. Let's give it a shot:

list[4] = "Crayons"

This will not work! But why, can you take a guess?

toy-bin-img-5

It's telling us that we cannot assign through subscript because list is a constant (we declared it using the let keyword). Ah! That's exactly how String and Int work. We decide whether or not we can change (mutate) the array based upon the let or var keyword just like every other type in Swift. Let's change the list array to a variable using the var keyword:

var list = ["Legos", "Dungeons and Dragons", "Gameboy", "Monopoly", "Rubix
Cube"]

After doing so, we should be able to run this code without any problem:

list[4] = "Crayons"

If we decide to print the entire array, we will see the following print to console:

["Legos", "Dungeons and Dragons", "Gameboy", "Monopoly", "Crayons"]

Note how Rubix Cube is no longer the value at index 4 (our last index); it has been changed to Crayons. 

That's how we can mutate (or change) elements at certain indexes in our array. What if we want to add a new item to the array, how do we do that? We've just saw that trying to use subscript syntax with an index that doesn't exist in our array crashes our application, so we know we can't use that to add new items to our array.

Apple (having created Swift) has created hundreds, if not thousands, of functions that are available in all the different types (like String, Int, and array). You can consider yourself an instance of a person (person being the name of the type). Being an instance of a person, you can run, eat, sleep, study, and exercise (among other things). These things are considered functions (or methods) that are available to you. Your pet rock doesn't have these functions available to it, why? This is because it's an instance of a rock and not an instance of a person. An instance of a rock doesn't have the same functions available to it that an instance of a person has.

All that being said, an array can do things that a String and Int can't do. No, arrays can't run or eat, but they can append (or add) new items to themselves. An array can do this by calling the append(_:) method available to it. This method can be called on an instance of an array (like the preceding list) using what is known as dot syntax. In dot syntax, you write the name of the method immediately after the instance name, separated by a period (.), without any space:

list.append("Play-Doh")

Just as if we were to tell a person to run, we are telling the list to append. However, we can't just tell it to append, we have to pass an argument to the append function so that it can add it to the list.

Our list array now looks like this:

["Legos", "Dungeons and Dragons", "Gameboy", "Monopoly", "Crayons", "Play-Doh"]

Summary

We have covered a lot of material important to understanding Swift and writing iOS apps here. Feel free to reread what you've read so far as well as write code in a playground file. Create your own arrays, add whatever items you want to it, and change values at certain indexes. Get used to the syntax of working with creating an arrays as well as appending new items. If you can feel comfortable up to this point with how arrays work, that's awesome, keep up the great work!

Resources for Article: 


Further resources on this subject: