Unit 14: Arrays & Loops Flashcards
Arrays & Loops
you use an array to hold a list of items of the same type, keeping them in order [e.g., “duck”, “duck”, “goose”]
Index
the numbered position of an item in an ordered collection; the first item’s index is always 0, and the index of the last item will equal the total number of items minus one
Literal
value that is either typed or inserted directly into code without initializers; e.g., literal string = “hello” / literal array = [1, 2, 3]; non literal string might be initialised with String(), whereas a non-literal integer might be initialised with homeTeamPoints + awayTeamPoints
Loop
runs the same code for each item in a collection
Pseudocode
used to describe code patterns without worrying about whether it follows the exact rules of the programming language; usually written using a mix of everyday language and code
Lists
People use lists all the time. You might have a to do list, a wish list, an iTunes playlist, even a bucket list. Lists are very useful and they’re common in coding too.
When you learned about strings, you created lists of things in some of the exercises. You made lists by joining multiple strings together with the \n newline character.
let shoppingList = “Eggs” + “\n” + “Tomatoes” + “\n” + …
This code gives you a list that displays nicely on the screen, but there’s not much else you can do with it. Think of some other things you might want to do with a list:
How could you call a function on each member of the list without needing to retype them all?
How could you double-check whether you’ve already added something to the list?
If your list has grown to hundreds of items, could you easily remove the one that says “Tomatoes”?
What if your list isn’t made of String values, but something else, like a list of prices that you’d like to add up?
What’s the first thing? The last thing? The 24th thing?
How many things are there?
How can you rearrange the list?
In Swift, a list is called an array.
Think of any iOS app you’ve ever used where you’ve scrolled through a list of things. That app is almost certainly using an array.
In this lesson you’ll learn about creating and working with arrays.
Array Literals
You’ve created strings, numbers and Boolean values directly in code using literal values. You can also create an array directly in code using an array literal.
Array literals are lists of items, separated by commas, with the whole thing inside square brackets:
let devices = ["iPhone", "iPad", "iPod", "iMac"] /*: Hover over the list in the results sidebar and use the circular Show Result button to add the array inline to the playground. In the inline view you can see that each item in the array has a number, beginning at zero, like this:
0 "iPhone"
\1 "iPad"
\2 "iPod"
\3 "iMac"
- experiment: Change the order or number of items in the
devices
array literal above. Notice that the order of the items in the results viewer always matches the order they’re entered in the literal. - experiment: Create a new constant named
highScores
below and assign it an array containing a list of ten numbers.
*/
// Define highScores array below
/*:
Move on to the next page to find out about what those numbers are for.
Indices
Here is an array of devices:
let devices = ["iPhone", "iPad", "iPod", "iMac"] /*: Use the Show Result button to view the result inline, like you did on the previous page. Each item in the array has a number next to it, starting at zero.
The number is known as the index of the item in the array and represents its position in line. In this case, "iPod"
is at index 2 of the devices
array. Since this array is defined using let
, both the items and the order of the items will never change. This means that no matter how many times you print this array, "iPod"
will always be at index 2.
- note: You’ll see the plural of “index” written sometimes as “indices” and sometimes as “indexes”.
Each item in an array has an index, starting with the first item at zero. You can get the value that’s stored at a particular index by putting the index in square brackets after the array name:
*/
// This gets the object at index 0
devices[0]
/*: - experiment: Declare a constant `favoriteDevice` and set its value to “iPod” by using an index into the `devices` array. */ // Declare favoriteDevice below
/*: Getting a value using the index has to be done carefully. If you ask for an item that is not in the list, you can cause a serious program error. It would be like telling someone to walk 100 feet down a dock that's only 50 feet long. If the person followed your instructions as strictly as a program executes your code, they'd end up walking right into the water.
- experiment: Try to get the item at index
4
in the list. Open the console for more information about the error. - /
//:
Count
This array contains a list of the chores that you have to get done:
let chores = ["Vacuuming", "Dusting", "Laundry", "Feed the dragons"] //: Each chore takes you 10 minutes to complete: let minutesPerChore = 10 //: How can you find out how long all of your chores are going to take? You need to know how many chores are on the list. You can find out the number of items in an array using the `count` property, which is an `Int`: let numberOfChores = chores.count let choresTime = numberOfChores * minutesPerChore //: Next learn how the type system in Swift handles arrays.\
Types
You’ve already learned how important types are in Swift and how useful they can be in helping you prevent errors in your code.
Of course, Array is a type, but an array type in Swift also includes the type of the values in the array.
Option-click on the two arrays below and look at their types
let grades = [“A”, “B”, “C”, “D”, “E”]
let starRatings = [1, 2, 3, 4, 5]
/*:
The [
and ]
brackets tell you that it’s an array type. Between the brackets is the name of the type of elements the array holds.
You can translate the type signature [SomeType]
into an English sentence by saying, “This array is a collection of SomeType instances.” If you Option-clicked on a name and saw [Instrument]
, for example, you could say “This array is a collection of Instrument instances.”
- callout(Exercise): What is the type of
grades
? What is the type ofstarRatings
?
*/
let someGrade = grades[0]
let someRating = starRatings[0]
//: Since arrays always know what kind of element they’re holding, you can pull out a single element from that collection and rely on type inference to establish thatsomeGrade
is aString
andsomeRating
is anInt
.
//:
//: - callout(Exercise): Try settinganotherGrade
to a number. What happens?
var anotherGrade = grades[1]
//: Next, learn how to work through the values in an array.\
Processing Arrays
When you group similar values into a collection, it’s usually because you want to do some work on each item.
Here’s an array:
let friends = [“Name”, “Name2”, “Name3”, “Name4”, “Name5”]
//: Now you can define a function to process each item in the array:
func invite(friend: String) {
print(“Hey, (friend), please come to my party on Friday!”)
}
//: And then call the function over and over again. Check the console for output:
invite(friend: friends[0])
invite(friend: friends[1])
invite(friend: friends[2])
//…
//: This code works, but leaves you with a few problems. You need to know how many things are in the array so you can decide when to stop calling the function. You also have to write the function calls over and over again. The more guests you want to invite, the more invite
functions you’d have to type. Isn’t the point of code that it can automatically do work for you? Plus, what if you accidentally mistyped a number and skipped a guest? How would you ever know?
//:
//: Luckily there’s a way to get Swift to do this work for you safely and quickly.\
Loops
Swift has a built-in way to let you run code for each item in an array. It’s called looping through the array.
Think of it like a roller coaster. The queue is the array. The car arrives, the first person from the queue gets on, goes around the loop, and gets off. Then the next person in the queue gets on for a turn. 🎢
When you loop through an array, you take one item, run some code using that item, then take the next item.
When the code is finished with all the items in the collection, the loop stops automatically and the code continues executing through the rest of the program.
To run code for each item in an array, you can use a for…in loop. Here is an array of friends that’s processed by loop:
let friends = [“Name”, “Name2”, “Name3”, “Name4”, “Name5”]
for friend in friends { let sparklyFriend = "✨\(friend)✨" print("Hey, \(sparklyFriend), please come to my party on Friday!") } print("Done, all friends have been invited.") //: The first line sets up the loop with two important pieces of information: //: 1. Which collection to work through (in this case, `friends`). //: 2. What to call the item being worked with (in this case, `friend`). //: You could say in English, “For every friend in the friends collection...” //: //: All of the code between the braces is the "body" of the loop. It’s the list of steps that will be run for each item in the collection. The first time through the loop, the value of `friend` is `Name`, and the second time through its value is `Name2`, and so on until the whole collection has gone through the loop. //: - experiment: The `friend` constant was defined as part of the `for` loop. What do you think will happen if you uncomment the line below? Will the result be the last name the loop used. Or will it return an error? //friend //:
Mutable Arrays
Recall that declaring a value with let means that the value cannot be changed (is immutable) and declaring with var means that it can be changed (is mutable). This applies to arrays as well. If you create an array using let, it’s immutable. Arrays created with var are mutable:
var transitOptions = ["walk", "bus", "bike", "drive"] //: You can assign a whole different array of items: transitOptions = ["rowboat", "paddle board", "submarine"] //: But you can’t change the type of items the array holds. Just like all variables, declaring a mutable array with `var` lets you change the values to whatever you’d like as long as they’re the same type. It’s like someone who's a picky eater declaring that they’ll eat anything as long as it’s some kind of pizza. //: //: This line would give an error because the items are `Int` values: //transitOptions = [44, 71, 16] //: Move on to change the contents of a mutable array without replacing the whole list.\
Adding Items
You learned earlier that an array of String values has the type [String].
Remember from the Instances playground that a type followed by parentheses is how you create an instance of that type. To create a mutable empty array that will hold strings, do this:
var list = String
//: Once you’ve created the array, there are several ways to add items to it. You can add a single item using the append
instance method:
list.append(“Banana”)
//: You can add an item at a specific index using the insert
instance method. As with everywhere you use an index, it has to be within the array or the program will crash:
list.insert(“Kumquat”, at: 0)
//: You can append a whole array of items using the compound assignment operator +=
:
list += [“Strawberry”, “Plum”, “Watermelon”]
//: - experiment: Practice adding items to the list using each of the three methods. Which do you prefer? When might you want to use each one?
//: Move on to find out how to remove items from an array.\
Removing Items
There are also several ways to remove items from mutable arrays. Each method updates the array and most return the item that’s been removed.
var numbers = [0,1,2,3,4] /*: You can remove items using the index. (Again, the index has to be within the array.)
The remove(at:)
method returns the item you have removed:
*/
let someNumber = numbers.remove(at: 2)
numbers
//: You can remove the first item using removeFirst()
:
let firstNumber = numbers.removeFirst()
numbers
//: You can remove the last item using removeLast()
:
let lastNumber = numbers.removeLast()
numbers
//: > Using removeFirst()
or removeLast()
on an empty array will cause an error.
//: You can remove everything using removeAll()
- this doesn’t return anything:
numbers.removeAll()
numbers
//: Next learn about replacing items in a mutable array.\