Instances, Methods, and Properties
Types enable you to understand what each value in your code represents. And type safety in Swift ensures that you use values of the right type in the right place. But types don’t just describe values. They can also define or describe the attributes and behaviors of a particular kind of thing—in other words, what a type is, or knows (its attributes), and what it does (its behaviors).
Consider the type Cat. It may have attributes such as breed, color, and age. It may have behaviors such as walking on four legs, purring, chasing lizards, and waking you up at 4:00 AM. A Cat type is different from a Dog type, although they have some similar attributes and behaviors. In Swift, the attributes of a type are called properties, and its behaviors are called methods.
Explore this:
Think about animals.
What other animal types can you describe? List as many properties and methods for each type as you can.
Even though the type describes the properties and methods of a particular kind of thing, each concrete example of the type—each cat, each rabbit—is a separate, independent instance of the type. For example, Chai, a three-year-old golden British Shorthair, is one instance of the type Cat. Her older sister Elsa, a four-year-old black British Shorthair, is another instance. Both instances of Cat have the same properties, but they may have different values for those properties.
Lists and Arrays
People use lists all the time. You might have a to-do list, a wish list, an iTunes playlist, even a bucket list. In Swift, such a collection is called an array—an essential component of coding. In fact, 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.
Lists are a way of organizing information by arranging items in order. Think about your bookshelf. You might organize your books by topic, by author, by size, or (why not?) by color. Whatever system you use, it’s still an ordered list. So when you ask a friend to grab a book, you don’t need to explain your system—you can just say, “It’s the third book from the left.”
In Swift, an array is a collection of individual instances of just one type. (List implementations in other languages may allow items of different types.) Each instance in the array is called an element. Each element in an array has a unique index, which identifies its location in the array respective to the first element, which is always located at index 0. In the same way, you can think of your bookshelf as a collection of instances of the type book, with the first book at index 0.
Explore this:
Think about collections.
Do you collect anything or know anyone with a collection?
- What type makes up the collection?
- How is the collection organized?
- Does each item in the collection have a specific location?
- How easily can you find a specific item in the collection?
Algorithms: Iteration
There may be times when you want to repeat certain steps in an algorithm over and over again. For example, you might play a game in which you keep taking turns, only stopping when a certain condition is true.
Based on how the game works, your changing score will determine what happens next—an example of selection. As long as the score is less than ten, you’ll take another turn. At the end of each turn, the algorithm will reevaluate the condition. When the score becomes greater than or equal to ten, the test will fail. At that point, the code will display “You win!”
In algorithms, repeating the same sequence of steps multiple times is known as iteration. In Swift, as well as all other programming languages, iteration is a critical building block of algorithms.
Remember—algorithms have three basic building blocks: sequencing, selection, and iteration. In this unit you'll explore how iteration lets you build even more powerful code.
Explore this:
Think about the game Snakes and Ladders.
Complete the flowchart to express the game play as an algorithm. Write out all the steps, and show where you might use sequencing, selection, and iteration.
How could you determine who had won the game?
Loops
The term for iteration in most programming languages, including Swift, is a loop. A loop defines a code segment that will be repeated—its body—and a determination for when to exit the loop. In Swift, there are several different styles of loops, including one for working with arrays. A common activity with an array is to do the same thing with each of its items. For example, you could look at each of the books on your shelf, noting whether or not you’ve read it. At the end, you’d have a list of all unread books, which you might use to prioritize which book you’ll read next or to calculate how long it would take to finish reading all the unread books on the shelf.
In Swift, you can work with an array by writing a loop that contains code to run for each element of the array. Think of looping through an array like a roller coaster with only one car, for only one person at a time. The roller coaster track, traveled by the car over and over, is the code segment in the loop. The line of people waiting to ride the roller coaster is the array. The car arrives, the first person from the line gets on, goes around the loop, and gets off. Then the next person gets on for a turn—a different item in the array going through the same loop.
Explore this:
Imagine your book collection contained every book you’d ever read, or every book you might ever want to read.
In that case, there are probably plenty of questions about your collection you couldn't answer just by glancing at the shelf.
- What questions might you ask about the collection?
- What code would you write to loop through the array?
Working with Arrays: Searches
It can be very useful to apply a function to every item in an array, but what if you just wanted to perform that function on one particular item? You would need to find that item’s location in the array—its index—and specify that you were performing the function on the item at that location. Finding an item in an array (or determining that it’s not there) is called searching, and there are multiple algorithms for performing a search on an array.
Thinking back to your book collection, imagine your friend wanted to borrow your copy of Pearls of Arrakhan. If your books weren’t organized according to a system, you could just tell your friend to read each title on the shelf until they came to the book they wanted. In programming, this is called a linear search, because each item is checked in turn to see if it’s true for the search value. As you can imagine, a linear search can be quite time-consuming, especially if your collection is very big and the item happens to be near the end.
If your collection were ordered alphabetically by title, your friend could do a much faster search. They could find a book near the middle of the collection, compare that book’s title to the one they’re searching for, and eliminate half the collection. Then they could repeat that process, cutting the results in half again each time.
For example, say the middle book in your collection is Of Mice and Men, which falls alphabetically before Pearls of Arrakhan. This means your friend can narrow their search to the second half of your collection. In that second half, if the middle book is Sputnik Sweetheart, they can rule out all books after that title. Each time they pick a book and compare the title to Pearls of Arrakhan, they can eliminate more and more of the collection. This type of algorithm is called a binary search. The best way to understand how a binary search works is to try it yourself.
Explore this:
Play guess-the-number.
Working in pairs, one person thinks of a number between 1 and 100. The other person tries to guess what the number is. With each guess, you are allowed to give feedback: "Too high!", "Too low!", or "That's it!"
What was your strategy for finding the number?
- How many guesses did it take?
- What is the maximum number of guesses you would need to guess a number between 1 and 100?
For a number between 1 and 100, it should take at the most 7 guesses to find the number. With twice as many numbers (between 1 and 200) it only requires one additional guess—the first guess would narrow the possibilities down to 100 numbers.
Can you determine the maximum number of guesses for every possible variant of this game?
Binary searches are more efficient than linear searches, especially with large amounts of data, but require that the data be in sorted order. Can you think of any types of values that wouldn’t lend themselves to a binary search?
Defining Your Own Types with Structs
You’ve learned about types and used them in your code. Types like Int and String are simple—they’re numbers and text. But if you want to describe something complex, like a song, you can’t just use a single value. A song has multiple attributes, each of which has a type. (Think of the Music app and how much data it stores about each song in your library.)
Explore this:
Think about the Music app.
List all the attributes of a song in the Music app, and define the type you’d use for each attribute.
For example, the type of songTitle would be String.
When you program in Swift, you aren’t limited to the built-in types. You can create types of your own that group lots of attributes together. For example, you could create a Song type to represent everything about a song, using existing types as building blocks. Then you can do things in your code, like create an array of songs.
A very common way to create a new type in Swift is to define a struct (short for structure.) When you make your own struct, you define properties that represent all the attributes of the thing they represent. So your custom Song struct would have properties like title, length, artist, and so on.
In the definition of your struct, you’ll also probably include methods to perform useful tasks, such as playing a song or adding it to a playlist.
Explore this:
Think back to the animal types you described earlier.
What if you were to create a custom type for a totally new kind of animal?
- What properties and methods would that custom type have?
- What would be an example of one instance of the type?