6

STORING COLLECTIONS IN DICTIONARIES AND ARRAYS

Image

In previous chapters, you learned that you can store a single piece of information in a variable or constant. But what if you want to store a collection of things, like the names of all the places you’ve visited or all the books that you’ve read? In this chapter, we’ll introduce you to arrays and dictionaries. They’re both used to store collections of values. Using arrays and dictionaries, you can work with a lot of data at once and make your programs more powerful!

KEEPING THINGS IN ORDER WITH ARRAYS

An array is a list of items of the same data type stored in order, kind of like a numbered grocery list. Items in an array are stored by their index, a number based on where the item is positioned in the array.

When you write a grocery list, you usually start with the number 1, but in computer programming, an index starts at 0, not 1. So the first item in an array is always at index 0, the second item is at index 1, the third item is at index 2, and so on.

Let’s create an array. If you already know what you’re going to put into your array, you can create it and initialize it with those values. To initialize something in Swift is to give it some initial value so you can use it in your program. Let’s say that you want to store a list of all of the national parks that you’ve visited. Enter the following into your playground:

This code creates an array variable called nationalParks and initializes it with the names of three national parks. Because we initialized this array to hold strings, you’ll only be able to put strings in it.

Figure 6-1 shows how you can imagine your array. It’s like a row of boxes containing the three names of national parks at indices 0, 1, and 2. Remember that the indices of an array always start at 0!

Image

Figure 6-1: The nationalParks array

USING MUTABLE AND IMMUTABLE ARRAYS

Our nationalParks array is a variable because we created it with the var keyword . An array stored in a variable is called a mutable array. This means that you can change it by adding items, removing items, or swapping items in and out.

You can also create an immutable array. An immutable array is created with the keyword let instead of var. Similar to a constant, once an immutable array is created, nothing in it can be changed.

So when should you use a mutable array or an immutable array? It’s best to use let if you know your collection will never change, like if you’re storing the colors of the rainbow. You should use var if you need to change your collection, like if you’re storing an array of your favorite T-shirts, which might change depending on what’s in style!

Image

USING TYPE INFERENCE

When we created our nationalParks array, we specified that we were creating an array of string values by adding a colon (:) and [String] . This step is optional when you create an array and initialize it with one or more values because Swift will use type inference to determine the kind of data you want the array to hold. That means that you could just as easily have created the array by doing this:

Using type inference, Swift knows we initialized this array to hold strings, and it can hold only strings.

The list of parks that we created the array with is an example of an array literal. A literal is a value that is exactly what you see. It is not a variable or constant but rather just the value without a name. "Grand Canyon" is an example of a string literal, and 7 is an example of an integer literal. An array literal is a list of items contained between two square brackets and separated by commas, like ["Acadia", "Zion", "Grand Canyon"] .

ACCESSING ITEMS IN AN ARRAY

Let’s say you want to access an item in your array and use it in your program. Your friend asks you to tell them all about your travels, so you want to use the names of the national parks that you stored in the array. To access an item in your array, write the array name followed by the item’s index inside square brackets:

In this example, we are accessing the names of the national parks and then printing them to the screen using print. To get the first item in nationalParks, you use nationalParks[0] . To access the second item in nationalParks, you use nationalParks[1].

WATCHING THE RANGE

One important point about arrays is that if you try to access an item at an index that’s higher than the last index in the array, you’ll get an error. In Figure 6-2, you can see that nationalParks[3] (which would be the fourth item in the array) gives you an error because there are only three national parks in the array, indexed from 0 to 2.

As you can see, you get an error message that says Index out of range. If you try to access an item that doesn’t exist in your array, your app will crash!

Image

Figure 6-2: Trying to access an index in the array where nothing exists causes an error.

ADDING ITEMS TO AN ARRAY

One way to change an array is to add new items to it. There are a few different ways to do this, so let’s take a look at each.

First, you can use an array’s append(_:) method. Append means to add something. Using append(_:), you can add one new item to the end of your array. Say you go on another trip and visit the Badlands, and you want to add it to your list of national parks. To do that, add this code into your playground:

To use the append(_:) method, first write the name of your array followed by a period and then append. Then, put the item you want to add to your array inside the parentheses. In this case, you put "Badlands" inside the parentheses.

If you want to add something at a specific place in your array, use the array’s insert(_:at:) method instead. This method takes two arguments: the item that you want to insert and the index of where it should go in the array. (We’ll discuss arguments in more detail in Chapter 7.)

Let’s say you totally forgot that you went to the Petrified Forest right after you visited the Grand Canyon, and you want to update your nationalParks array so it displays the parks in the order in which you visited them. To update your array, you could use the insert(_:at:) method to put the Petrified Forest in the right position:

When you insert a new item at index 3, everything that was in the array at index 3 or higher gets scooted over to make room for the new item. That means the item that was at index 3 is now at index 4, the item that was at index 4 is now at index 5, and so on. After you add the Petrified Forest, nationalParks is now ["Acadia", "Zion", "Grand Canyon", "Petrified Forest", "Badlands"].

COMBINING ARRAYS

Not only can you add new items to an array, but you can also add two arrays together using the + and += operators. Let’s say that you have the ingredients for a fruit smoothie in two arrays:

Now you can make a delicious smoothie by adding the fruits and liquids arrays.

The order of the ingredients in smoothie is the same as the order in fruits and liquids. If you created smoothie with liquids + fruits, then the liquids would come first.

You use the += operator to add an array to the end of your array. Add some whipped cream as follows for extra yumminess:

Note that ["whipped cream"] is an array even though it has a single item in it. When you’re using += to append something to an array, you have to make sure you’re only trying to add another array. If you were to just write the string "whipped cream" without the square brackets around it, you would get an error.

Image

REMOVING ITEMS FROM AN ARRAY

There are several methods for removing items from an array. Let’s start by looking at the array’s removeLast() method. As you might have guessed from its name, removeLast() removes the last item from your array. Let’s try it out with a shoppingList array:

Neat! Note that the removeLast() method returns the removed item, so you can store it in a new constant or variable if you want.

You can also remove an item from a specific index by using the remove(at:) method. Let’s say that your mom doesn’t want you buying any candy and takes that off the list:

Image

Just like when we added an item to the middle of our array and all the items scooted over to make room, if you remove an item from the middle of an array, the rest of the items will scoot back to fill in that empty space. The "apples" item that was at index 3 is now at index 2, where "candy" was.

You can also remove all items from an array with removeAll(). Try entering this into your playground:

Note that trying to remove an item at an index that doesn’t exist will give you an error:

Our array doesn’t have this many items (in fact, now it’s empty!), so this throws an error. We’ll also get an error if we use removeLast() on our empty array, because there’s nothing in it—there’s no last index at all! However, removeAll() is always safe to use, even on an empty array.

REPLACING ITEMS IN AN ARRAY

To replace an item in an array, you set the index of the array to the new value, as shown here:

At , we replaced the item at index 2 (the third item) with "Unicorn" because magical animals count as favorite animals, too! At , we replaced the item at index 0 (the first item) with "Bearded dragon". No, that’s not a real dragon—it’s just a lizard!

Like any time you’re working with array index numbers, you have to be sure an item exists in the array at that index before you change its value, or you will get an Index out of range error.

Figure 6-3 shows the error that occurs if you try to add "Standard poodle" using favoriteAnimals[3] = "Standard poodle". To add an item to the end of an array, you should use the append(_:) method or +=, as we covered in “Adding Items to an Array” on page 70.

Image

Figure 6-3: Don’t try to replace a value at an index beyond the existing array.

Now you know how to change arrays however you might need to. You can add items, take items away, or replace items. Next, we’ll look at how to use the properties of arrays to find out even more information about them.

Image

USING ARRAY PROPERTIES

In addition to methods like append(_:) and removeLast(), arrays also have properties. An array’s properties are variables or constants that contain some information about the array. Two really helpful properties that you might use are the Boolean property isEmpty and the integer property count.

The isEmpty property is true or false depending on whether the array is empty, and the count property will tell you how many items are in that array.

Check out how these two properties are used in the following if-else statement:

Image

This if-else statement checks whether the array mySiblings is empty . If it is, then "I don't have any siblings." is printed. But if there is something in the array, then the number of siblings that we have is printed: "I have 3 siblings." .

LOOPING OVER AN ARRAY

Sometimes when you’re working with arrays you might want to do something to every item in the array. You can use a for-in loop to do that! The following code will print every topping in a pizzaToppings array on a separate line:

Image

To write a for-in loop for the pizzaToppings array, we used the keyword for, followed by the constant topping, then the keyword in, and finally the name of our array, pizzaToppings. Then we put the statements that we want to run for each topping inside the braces of the for-in loop. The constant topping temporarily represents each pizza topping in the array as we loop through it. We could have chosen any name for this constant, but it’s a good idea to pick something that makes sense. You can see the output of this for-in loop in Figure 6-4.

Image

Figure 6-4: Output of the example for-in loop

Image

Using for-in loops is great for printing every value in an array. If you’re working with numbers, you can even use them to perform math operations on each item, which makes for some speedy calculations! The following code takes an array of numbers and calculates the square for each (the square of a number is that number multiplied by itself):

Image

Figure 6-5 shows the results.

Image

Figure 6-5: Printing the squares for each number in the myNumbers array

DICTIONARIES ARE KEY!

A dictionary is also a collection of values, but instead of an ordered index, each value has its own key. Because there’s no index, the values are not stored in any particular order. To access values in a dictionary, you look them up by their key.

A key must be unique. You can’t have the same key more than once in the same dictionary. If there were two identical keys and you asked the computer to give you the value for one of them, the computer wouldn’t know which one to choose!

Let’s take a look at how to make a dictionary and write keys that will help you find all the information you need.

Image

INITIALIZING A DICTIONARY

To create and initialize a dictionary, first write var and the name of your dictionary. Then write the keys and corresponding values inside a pair of square brackets, similar to an array. Let’s create a dictionary to store the names of a few US states. The key for each state will be its two-letter abbreviation:

As you can see, there’s a colon between each key and its value, and the key/value pairs are separated by commas.

Dictionaries are different from arrays in that they are unordered. Because of that, it’s likely that the order of the states that you see in your results pane is different from the order in which you entered your states . It might even be different than the order that’s printed in this book!

As with arrays, you can use var to make a mutable dictionary or use let to make an immutable dictionary.

In Swift, all of the keys of a dictionary must be the same type, and all of the values of a dictionary must also be the same type, but the key type doesn’t have to match the value type. For example, if you wanted to store a collection of fractions, you could use doubles for the keys and strings for the values:

In this dictionary, all of the keys must be doubles, and all of the values must be strings. Again, you’ll see that the order of the numbers in the results pane can be quite different from the order in which you wrote the fractions in your dictionary. This is fine because you don’t need to know the order to access anything. You can find any item that you need by its key. Let’s see how!

ACCESSING VALUES IN A DICTIONARY

Looking up a value in a dictionary is similar to how you access a value in an array except that you use a key inside the square brackets instead of an index, like this: usStates["TX"].

There is a big difference, however, in how Swift returns the values from a dictionary. When you access a value at an index of an array, you are simply given the value. When you access a value with a key in a dictionary, you are given an optional.

In Chapter 5, you learned that optionals might contain a value or might be nil. The reason Swift returns optionals when you’re looking up items in a dictionary is that the key you used might not exist in the dictionary, in which case there’s no value to access. Trying to access a value that doesn’t exist would give you a big fat error! To avoid that problem, Swift returns optionals. That means you need to unwrap any value you get out of a dictionary before you can do anything with it.

To unwrap an optional, first you check whether it exists using an if-let statement, just like we did in Chapter 5. The following code shows you how to get a value out of a dictionary:

Image

To retrieve "Texas" from the dictionary, we use if let to set a constant loneStarState to usStates["TX"] . Because we have this state in our dictionary, the line I have Texas in my dictionary. is printed. Next we try to access a state that is not in our dictionary by using the key usStates["FL"] . Thankfully, because we used an if-let statement, the program won’t crash when the computer can’t find this state. Instead, I don't have that state in my dictionary. is printed.

ADDING ITEMS TO A DICTIONARY

To add an item to a dictionary, first write the name of your dictionary and assign the new item to the key you want it to have in the dictionary. Let’s add "Minnesota" to our usStates dictionary:

Now when you look at usStates, you’ll see that it’s updated to ["MN": "Minnesota", "WA": "Washington", "MA": "Massachusetts", "TX": "Texas"]. Remember, because you don’t have to rely on indices, your new dictionary item might appear anywhere in the dictionary.

REMOVING ITEMS FROM A DICTIONARY

Removing an item from a dictionary is quite simple; you do so by setting the value to nil. Because the values in dictionaries are returned as optionals, you don’t have to worry about nil causing any problems in your dictionary.

You can see that after you remove the value at the key "MA", usStates is updated to ["MN": "Minnesota", "WA": "Washington", "TX": "Texas"]. Remember that nil is special and means that there’s no value at all. That’s why you don’t see "MA": nil in our dictionary.

REPLACING ITEMS IN A DICTIONARY

Replacing an item in a dictionary is also easy. It works the same was as replacing an item in an array. You just set the item that you want to replace to something else. Say you create a dictionary of fruit colors:

At first we had the value "apple" for "red", but then we decided that "raspberry" is a better fruit to use since sometimes apples are green or yellow. To replace "apple" with "raspberry", we set colorFruits["red"] to its new value .

You may remember that this is the same way we entered a new value into a dictionary. If the key already exists in the dictionary, then the value for that key is replaced. If the key doesn’t already exist, then the new key/value pair will be added to the dictionary.

Image

USING DICTIONARY PROPERTIES

Like an array, a dictionary also has an isEmpty property and a count property. For example, the following code shows how you can use the isEmpty property to check if a dictionary is empty, and if it isn’t empty, the count property checks how many items you have. Imagine you have a basket of fruit for sale. You can use these properties to help you keep track of everything:

Image

A dictionary also has two special properties: keys, which contains all of the dictionary’s keys, and values, which contains all of its values. We’ll use these two properties when we loop through the dictionary.

Let’s write some code that loops through our fruit baskets and prints the price of each fruit.

LOOPING OVER A DICTIONARY

You can loop through a dictionary using a for-in loop. Because each item has a key and a value, you can do this in two different ways. This is how to loop through a dictionary using its keys:

Image

Here we use the dictionary’s keys property to loop through fruitBasket and print its contents. We start by writing the keyword for, followed by a constant name fruit for the dictionary key, the keyword in, the dictionary name, a period, and keys.

Inside the braces of our for-in loop, we have access to both the key, which we call fruit , and the value at that key when we force-unwrap its contents with fruitBasket[fruit]! . That value will be the fruit’s price.

In this case, it’s safe to force-unwrap the value using an exclamation point because we know that the fruit key we’re using is definitely inside the dictionary.

Any code we put inside the for-in loop will run once for every key in our dictionary. So you should see the print statement display three times.

We can also loop through the dictionary using its values property:

Image

We use the same style of for-in loop, but now we use a constant to refer to each value, which we call price, in the values property. When looping through values, we don’t have access to the keys from inside the loop.

Another difference to note is that price is not an optional because it’s accessed directly as a value in the fruitBasket dictionary. That means we don’t have to unwrap it. You should still see the print statement printed three times. Figure 6-6 shows the output of both loops.

Image

Figure 6-6: Looping through the keys and values of a dictionary with a for-in loop

The order of your results might be slightly different from ours. That’s because the items in a dictionary aren’t in a numbered order like they are in an array! And because the order is not guaranteed, you might see a different order printed if you run the same code again.

WHAT YOU LEARNED

In this chapter, you learned how to store collections of items in an array and in a dictionary. To store items in an ordered list, you would use an array and look up each item by its index. If you wanted to store items by key instead, you would use a dictionary.

Knowing about arrays and dictionaries and how to use them is a powerful building block for almost any programming language. Next we will learn about functions, another very powerful tool. Functions are blocks of code that you create and name to perform a specific job. After you have written a function, you can use its name to call it from almost anywhere in your program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset