How to use Arrays in Swift – iOS Mobile Development

You can access the full course here: iOS App Development for Beginners


So far, all of the variables that we have seen can only hold one (or zero) values. However, we sometimes need to be able to store multiple values so that we can carry them around in a single variable rather than porting multiple variables around. To do this, we can use an array. This is essentially a list of values. Arrays also have a lot of functionality attached to them to help retrieve or modify certain values or attributes. We won’t explore all of the functions, but we can go over some of the more commonly used ones. First, to create an array, we create a variable but store multiple values within []. We can store values all of the same type or of a single type. Here are some examples:

let testAnswers: [Bool] = [true, false, false, false, true]
let languages = ["Swift", "Java", "HTML"]
let random = [1, false, “hello”, 5.5]

If we want to fetch or modify a single value, we can do so by its index. Indexing is 0 based so the first element is at index 0 and the last is at index of (length – 1). To fetch an item, call upon the index inside of [] beside the name of the array. For example:

let testAnswers: [Bool] = [true, false, false, false, true]
let firstAnswer = testAnswers[0]

This stores the very first value (true) in firstAnswer. There is no built in check to make sure the item exists so be sure to not call an item that doesn’t exist like this:

let languages = ["Swift", "Java", "HTML"]
let someLanguage = languages[5]

You can implement some logic to make sure this doesn’t happen such as checking the length of an array. Do so with arr.count like this:

let languages = ["Swift", "Java", "HTML"]
let languagesLength = languages.count

Modify items using the same methodology. For example, if we wanted to change one of the test answers, we could do this:

var testAnswers: [Bool] = [true, false, false, false, true]
testAnswers[3] = true // testAnswers = [true, false, false, true, true]

As there are many functions, we won’t go over all of them but I’ll provide some examples of some common functions below:

var languages = ["Swift", "Java", "HTML"]
languages.append("CSS") // languages = ["Swift", "Java", "HTML", "CSS"]
languages.insert("Javascript", at: 2) // languages = ["Swift", "Java", "Javascript", "HTML", "CSS"]
languages.remove(at: 3) // languages = ["Swift", "Java", "Javascript", "CSS"]
var firstLanguage = languages.first // firstLanguage = "Swift"

For the last one, it is important to note that firstLanguage is of type String? Because the first element will not exist if the array is empty. We will explore more functions as we go but for a list of all functions, simply type the arrayName. And then you will see a list of functions.

As a quick aside, we can also create ranges of integers with the range operator. To create an inclusive range specify startIndex…endIndex and for an exclusive range specify startIndex..<endIndex. Some examples are:

0...5 // 0, 1, 2, 3, 4, 5
0..<5 // 0, 1, 2, 3, 4

Note that these are not arrays; they are ranges that have slightly different properties and functions.



What’s up everyone, welcome to part seven of our iOS Development Course, this will be all about arrays. We’ll talk about first, what arrays are, and then how we can use arrays. We’ll also explore some extra array functions, as arrays are special and have a lot of extra functionality attached to help modify, or retrieve, properties or values within an array.

So for starters, what are arrays? They’re essentially just lists of values. We treat them like regular variables, except that they hold multiple values in a single location. Each of the items in an array is stored at a specific index or a specific position. Indexing starts at zero, so the very first element is at index zero, and the very last one is at the length minus one. We fetch, or modify, individual items within an array, by their index. So if we want to change just one of the values within an array, we have to find its index, and then we can modify it.

We can also call upon multiple functions to, again, get or change items or properties within an array. Now, there are many, many functions attached to arrays, so we’ll just go over a few of the basic ones and I’ll leave the rest up to you to explore.

So let’s head on over to the code now. As you can see, I’ve got my Playground up and running again. So this is the iOS Development Playground, I have the project just down here. So let’s talk first about general arrays. Now, the way we set them up is actually very similar to variables. We either call upon and constant or a variable name, and then the name of the array, and then we assign the value.

So let’s try to think about some places where we might have lists within our code. So one of the most common examples that gets brought up when talking about arrays, or lists, is a grocery or a shopping list, so it’s just gonna be a bunch of strings. So let’s create that now, let’s set it to be a variable so that we can modify it, and we’ll call this groceryList. It’s type, although, again, this isn’t needed is going to be an array of strings, like so. And then we set it equal to a list.

So all of the items within an array go within these square brackets, and they’re separated by commas. So let’s say the very first item is gonna be apples. The next item might be bread. After this, maybe we want some cheese or something, and let’s just go with this. So I have the three items within our list, it doesn’t matter, by the way, if they’re up or down, or side-by-side, I just find it easier to read this way. Let’s kinda close that up, I’m not sure why that’s going weird.

So we have a list of strings here, we can access and modify the entire list by doing groceryList, and then setting it equal to something else if we really want, but in this case, we are fine with how it is. So that’s how we can get the entire list by calling upon it just like a variable. But if we want just a single item within the list, we have to get its index. Remember, indexing is zero-based, so this is index zero, index one, and index two.

So let’s say we wanna fetch the very first item, we get our groceryList, and we put the square brackets beside it, and then here we put the index of the item we want to retrieve. So this compiler’s impatient, and it’s waiting for us to do that. So if we want the first item, that’s gonna be index zero, like so. So we can retrieve it, we can store it in something, maybe this is going to be firstGrocery is equal to our groceryList of zero. So what do you think the value should be? Well, it should be apples, it’s going to retrieve basically the item, that it finds in that index, and you can see that it is, indeed, apples. Again, we don’t have to assign the type, although we can say it’s specifically a string, if we’d like.

You should take note of the fact that there’s no array bounds checking. So if we tried to do like groceryList, at the index of five or something, this isn’t gonna work. This is actually gonna throw us an error because this is out-of-bounds. The groceryList is only three items long and here we’re calling for the sixth item in this groceryList. So you always want to check your length before you call upon the index. You can do so simply by doing the grocery, actually the groceryList, dot and then count. So count returns a number of items in the array. When you’re fetching items, always make sure that the index you’re retrieving is less than the count, okay, so just a heads up there.

All right, what about setting items? Well, we do the exact same thing, we get the groceryList, or the array name. In the square brackets, we put the index of the item we want to change, maybe we’re gonna change bread to bagels. So we’re gonna set this, and we’re going to say it’s equal to, maybe we want some bagels. So now let’s take a look our groceryList. This should now say apples, bagels and cheese. And indeed it does, apples, bagels and cheese, like so. So that’s how to access or modify individual items.

Now, I did say that arrays come with a suite of other functionality. In fact, you can access the entire list of functions simply by selecting an array names, so in this case, groceryList, doing dot, and then you can see there are a bunch of different functions here. So many of these are properties, they just retrieve information about the array, such as accounts or the very first element. Note that it’s optional, because the first element may or may not exist. If the list is empty, then this will return nil. Or you can get the last index, you can get the min or max, et cetera, or a lot of these functions help to modify the array in some way. So this means adding items to it, removing items from it, inserting items, et cetera.

So let’s say we want to add an item. I’ll just go over the three common operations adding, inserting and removing. So we can append an entire array, or we can just append one element. This basically sticks an item onto the end. So we want to append let’s say we decided we want eggs, as well. Do we, no, no we don’t have that. So if we print out grocery list, we should see that it contains the four items with eggs, as well. Cool stuff.

Let’s say we want to insert something so we can do groceryList. Actually, let’s go up here, groceryList, dot, insert. And now this takes two arguments. It needs a new element, and it needs a specific index. So let’s say we want to place it second we realize there’s apples, then something then bread and cheese, maybe we want I don’t know, some bananas. Bananas, and we want this at index one because we want to insert it right here. So we go zero, and then one, and that’s where we insert it. And we print out our grocery list, we can go ahead. And we can see that this should contain bananas, as well. Cool stuff.

So what about removing items? Well there’s two ways we can do that. Well, there’s actually multiple ways we can do that. We can remove at a specific index, we can remove everything, we can remove the first, we can remove the last, we can also pop the last element. So in groceryList, dot, popLast, that also does basically the same thing, we’ll stick with the remove function.

So let’s say we want to remove at a specific index. Note that it also returns the element that it’s removing. So let’s say we realize that we no longer need cheese, we have a bunch at home already, so let’s figure out what index that is that is gonna be, I believe, index, let’s pull this out. So we got apples, bananas, bagels and cheese, that’s in index three. So we want to remove the item in index three. We can go ahead and run this and this is now going to return our separation, so it’s going to return cheese. And at this point in time, groceryList has only apples, eggs and then bagels. Or, no, maybe it’s the other way around. I think at this point in time, it would be apples, bananas, and then bagels and then eggs.

So that was pretty much all we wanted to go over. We’re within our time limit, so I’m gonna end it here. Just remember, arrays are lists of items, each item is at a specific index, so it’s important for us to keep track of what items are at what index. We access them to either fetch them or to modify them. We just enter the index, which is zero-based. There’s a bunch of other functions that help us to retrieve properties or to manipulate the array in some way. What I recommend you do is actually explore some of those other array functions. I’ll give you a homework assignment at the end of the next section because we’re gonna be covering dictionaries and the two go really hand-in-hand. So we’ll end it here, thanks for watching, I will see you in the next one.

Interested in continuing? Check out the full iOS App Development for Beginners course, which is part of our Mobile App Development Mini-Degree.