Unit 14: Arrays & Loops Flashcards

1
Q

Arrays & Loops

A

you use an array to hold a list of items of the same type, keeping them in order [e.g., “duck”, “duck”, “goose”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Index

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Literal

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Loop

A

runs the same code for each item in a collection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Pseudocode

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Lists

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Array Literals

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Indices

A

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.
  • /

//:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Count

A

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.\
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Types

A

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 of starRatings?
    */
    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 that someGrade is a String and someRating is an Int.
    //:
    //: - callout(Exercise): Try setting anotherGrade to a number. What happens?
    var anotherGrade = grades[1]

//: Next, learn how to work through the values in an array.\

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Processing Arrays

A

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.\

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Loops

A

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
//:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Mutable Arrays

A

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.\
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Adding Items

A

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.\

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Removing Items

A

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.\

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Replacing Items

A

You’ve seen how to add and remove items from a mutable array. What if you need to replace one item with another?

Earlier, you saw how to access an item in an array by using its index:

var flavors = [“Chocolate”, “Vanilla”, “Strawberry”, “Pistachio”, “Rocky Road”]

let firstFlavor = flavors[0] // Remember, the first item is at index 0
/*:
 In Swift, the part of the statement `[0]` is called a _subscript_.
 With a mutable array, you can use the subscript to set the value at an existing index, replacing the value that is already there:
 */

flavors[0] = “Fudge Ripple”

let newFirstFlavor = flavors[0]

/*:
 - experiment: Change the value of "Pistachio" to a flavor of ice cream that’s not already used in the array, like “Mint Chocolate Chip.” Check the results sidebar to make sure you’ve made the change.
*/
// Change "Pistachio" to another flavor.
/*: 
 If you try to use an index that is not contained in the array, you will get an error. You can only replace values in a mutable array using subscripts, you can’t add or remove things.
 - experiment: In the statement below, what’s the highest number you can set the subscript to without receiving an error. Why is that the highest number you can use?
*/
flavors[1] = "Maple Walnut"

//:

17
Q

Wrap Up

A

You can use arrays to hold lists of items. Arrays have two key features:

The items in the array are all of the same type.
The items in the array are in a specific order.

Because of these two features, you can access items from specific points in the array using the index, and you’ll always get back a value of a known type.

Here are some other things you’ve learned about arrays:

The first index of an array is zero, not one.
Accessing arrays using the index can be dangerous. If the index used is outside the bounds of the array, your program will crash.
You can find out the number of items in an array using the count property.
You can use for…in loops to safely access each item in the array in order, without needing to know how many items the array contains.
Mutable arrays allow you to add, remove, and replace items.

Practice what you’ve learned with the exercises.

18
Q

Exercise: Count

A

If you try to use an index that’s outside of the array, your program will crash with a “fatal error.” How can you make sure this doesn’t happen?

You can find out the number of items in an array using the count property:

let devices = [“iPhone”, “iPad”, “iPod”, “iMac”]
devices.count
//: The only safe indices to use for an array are those less than the count.
//: - callout(Exercise): Using what you’ve learned about making decisions, write an if statement that will only access the array if the value of index is less than the array’s count. Uncomment and update the code below, then update the index constant to different numbers and see the results.
let index = 3
//if {
devices[index]
//}

19
Q

Exercise: Karaoke Host

A

You have a friend who loves singing karaoke with a big group of people. The karaoke singers add songs they’d like to sing to a list and the karaoke host calls out the songs one by one.

Your friend and has asked you to write software to help manage the song list.

Create an empty array to hold song titles as strings, and use the append method to add three or four songs one at a time.

Write a for…in loop and, for every song title in the array, print an encouraging announcement to let the next singer know that it’s their turn.

After the loop has called everyone up to sing, use the removeAll method on the song list to clear out all the past songs.

20
Q

Exercise: Counting Votes

A

You’re implementing a poll app for your class. You start with a basic yes-no question counter and now you have your first batch of answers back, parsed into arrays below.

This is a lot of data! But don’t worry too much about the long arrays. Whether you’re planning to loop over two items or two thousand, you’ll write the loop in exactly the same way.

let shouldMascotChangeVotes: [Bool] = [false, false, false, true, false, true, true, true, false, true, true, true, true, false, true, true, false, true, true, true, false, true, true, true, true, true, true, true, false, true, false, true, false, true, true, false, false, true, true, false, false, true, true, true, false, true, false, true, true, false, true, true, false, true, false, false, true, false, true, true, false, false, true, false, true, true, true, false, true, true, false, false, true, false, true, true, false, false, false, true, false, true, true, false, true, true, true, true, true, true, true, false, true, false, true, false, true, true, true, true, true, true, true, false, true, true, false, true, true, true, true, true, true, true, false, true, true, false, true, true, false, true, true, true, true, true, false, false, false, false, true, true, true, false, true, true, false, false, true, false, false, true, true, true, true, false, true, true, true, true, false, true, true, false, true, false, false, true, true, false, true, false, false, false, true, false, false, false, true, false, true, true, false, true, true, false, true, true, true, false, false, false, true, false, true, false, true, true, true, true, false, true, false, false, true, true, true, true, true, false]

let shouldInstallCoffeeVendingMachineVotes: [Bool] = [true, true, false, false, false, true, true, false, true, true, true, true, false, true, false, false, true, false, true, false, true, true, false, false, false, false, false, true, true, true, false, false, true, true, false, true, true, true, true, false, true, false, true, true, false, false, false, false, false, false, true, false, true, true, false, true, true, true, true, false, false, true, true, false, false, false, false, true, true, false, false, true, true, true, true, false, false, true, true, false, true, false, true, false, true, true, true, false, true, true, true, false, false, false, false, false, false, false, false, false, false, false, true, false, true, false, false, true, true, false, true, false, true, true, true, false, false, false, false, false, false, true, true, false, false, true, true, true, true, true, true, false, false, false, true, true, true, true, false, false, false, true, true, false, true, true, true, false, false, true, false, true, false, true, false, false, true, false, true, true, true, true, true, true, true, false, true, false, true, true, false, false, true, false, false, true, false, false, false, true, false, true, true, true, false, false, false, false, false, false, true, false, true, false, true, true, false, false, false, true]

let shouldHaveMorePollOptionsVotes: [Bool] = [false, false, true, true, false, true, false, false, false, false, false, false, true, false, true, true, false, true, true, false, false, true, true, false, false, false, false, false, false, false, true, false, false, false, false, true, false, false, false, false, false, false, true, true, false, true, true, false, true, false, true, true, false, false, false, false, true, false, true, true, false, false, false, false, true, true, true, true, false, true, false, false, true, true, false, false, false, false, false, false, true, true, false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true, true, true, false, false, true, false, true, false, false, false, true, false, true, true, true, true, true, true, true, false, false, false, false, true, false, false, false, false, false, true, false, false, true, false, false, true, false, false, true, false, false, true, false, false, true, false, false, false, false, false, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, false, false, false, false, true, true, true, true, false, true, true, false, false, true, false, true, true, false, false, true, true, false, true, false, false, false, true, true, false, false]

//:This is too many votes to tally quickly by hand, so you’ll write some code to tally it for you.
//:
//: - note:\
//: This is also a lot of votes for Swift to use type inference to determine what kind of array it has. The type annotation is written in the array literals above to tell Swift the type of array. This prevents the playground from running slowly.
//: - callout(Exercise): Create two variables, one to count `yes` votes and one to count `no` votes. Each should start off with a value of zero.
//:

//: - callout(Exercise): Create a for…in loop that loops over one of the vote collections and checks the value of each vote. If the vote is true, the loop should add one vote to the yes variable. If it’s false, it should add one vote to the no variable.

//: - callout(Exercise): After the loop has finished, write an if statement that compares the two values and prints a different message based on whether the vote passed or failed.

//: - callout(Exercise): Test your code by calling the `for…in` loop on each of the vote collections.\
//:Which measures won by popular vote?
/*:
 ### Extension:
 Your `for…in` loop would be even more powerful if you could easily reuse it. The easiest way to reuse code is to put it in a function.
 - callout(Exercise): Write a function that takes two arguments: a string describing the issue being voted on and an array with the issue's `Bool` votes. Move the `for…in` loop and the `if` statement *inside* the function, so it prints the results when you call the function with a particular issue's arguments. You should be able to call the function like this:
 ```
 printResults(forIssue: "Should we change the mascot?", withVotes:shouldMascotChangeVotes)
 ```
 A message like this should be printed to the console:\
 `Should we change the mascot? 54 yes, 23 no`
 */
// Add your vote-processing function here:
21
Q

Exercise: Goals

A

Think of a goal of yours that can be measured in progress every day, whether it’s minutes spent exercising, number of photos sent to friends, hours spent sleeping, or number words written for your novel.

Create an array literal with 20 to 25 items of sample data for your daily activity. It may be something like let milesBiked = [3, 7.5, 0, 0, 17 … ] Feel free to make up or embellish the numbers, but make sure you have entries that are above, below and exactly at the goal you’ve thought of. Hint: Make sure to choose the right kind of array for your data, whether [Double] or [Int].

Write a function that takes the daily number as an argument and returns a message as a string. It should return a different message based on how close the number comes to your goal. You can be as ambitious and creative as you’d like with your responses, but make sure to return at least two different messages depending on your daily progress!

Write a for…in loop that loops over your sample data, calls your function to get an appropriate message for each item, and prints the message to the console.

22
Q

Exercise: Screening Messages

A

You’ve somehow come to possess a huge list of messages about a series of characters: Caterpillar, Dormouse, Cheshire Cat, and others. The list is contained in the aliceMessages constant below.

Try to print out the aliceMessages array to see the whole list, but beware: It’s large enough that it may cause your playground to run slowly.

import Foundation

aliceMessages

/*:
 The Caterpillar has asked you to go through the messages and to relay any that contain the Caterpillar's name. Instead of reading all the text yourself, you decide to write more code to help.
  • callout(Exercise): Create a for…in loop to process the aliceMessages collection.\
    In the body of the loop, check whether each message contains the string “Caterpillar”.\
    If the message refers to the Caterpillar, print it to the console.
 - note:\
 The `contains` method is part of the `Foundation` framework that you read about in the “Types” playground. If you try using it and get an error saying “Value of type 'String' has no member 'contains',” follow the instructions from that playground to import the framework into your project.
 */
// Write the `for…in` loop here:

/*: