Protocols and Delegates
Congratulations! You are acquiring the skills to become an iOS developer! However, iOS developers need to understand two additional topics in order to be successful: protocols and delegates. It is not uncommon for new developers to get overwhelmed by these topics, which is why we introduced the foundational topics of the Swift language first. After reading this chapter, you will see that protocols and delegates are really useful and not hard to understand and implement.
Multiple Inheritance
We discussed object inheritance in Chapter 2. In a nutshell, object inheritance means that a child can inherit all the characteristics of its parent, as shown in Figure 12-1.
Figure 12-1. Typical Swift inheritance
C++, Perl, and Python all have a feature called multiple inheritance, which enables a class to inherit behaviors and features from more than one parent, as shown in Figure 12-2.
Figure 12-2. Multiple inheritance
Problems can arise with multiple inheritance because it allows for ambiguities to occur. Therefore, Swift does not implement multiple inheritances. Instead, it implements something called a protocol.
Apple defines a protocol as a list of function declarations, unattached to a class definition. A protocol is similar to a class with the exception that a protocol doesn’t provide an implementation for any of the requirements; it describes only what an implementation should look like.
The protocol can be adopted by a class to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.
Protocol Syntax
Protocols are defined like classes are, as shown in Listing 12-1.
If a class has a superclass, you list the superclass name before any protocols it adopts, followed by a comma, as shown in Listing 12-2.
The protocol also specifies whether each property must have a gettable or gettable and settable implementation. A gettable property is read-only, whereas a gettable and settable property is not (shown earlier in Listing 12-1).
Properties are always declared as variable properties, prefixed with var. Gettable and settable properties are indicated by { get set } after their type declaration, and gettable properties are indicated by { get }.
Delegation is a design pattern that enables a class or structure to hand off (or delegate) some of its responsibilities to an instance of another type. This design pattern is implemented by defining a protocol that encapsulates the delegated responsibilities. Delegation can be used to respond to a particular action or to retrieve data from an external source without needing to know the underlying type of that source.
Listing 12-3 defines two protocols for use with a random number guessing game.
The RandomNumberGame protocol can be adopted by any game that involves random number generating and guessing. The RandomNumberGameDelegate protocol can be adopted by any type of class to track the progress of a RandomNumberGame protocol.
Protocol and Delegation Example
This section shows you how to create a more sophisticated random number guessing app to illustrate how to use protocols and delegation. The app’s home view displays the user’s guess and whether the guess was high, low, or correct, as shown in Figure 12-3.
Figure 12-3. Guessing game app home view
When the users tap the Guess Random Number link, they are taken to an input screen to enter their guess, as shown in Figure 12-4.
Figure 12-4. Guessing game app user input view
When the users enter their guess, the delegate method passes the guess back to the home view, and the home view displays the result.
Getting Started
Follow these steps to create the app:
Figure 12-5. Creating the project
Figure 12-6. Turning off Auto Layout
Figure 12-7. Embedding the View Controller in a Navigation Controller
Figure 12-8. Outlets necessary to control the view
Figure 12-9. Create the Guess View Controller and objects
Figure 12-10. Create the GuessInputViewController.swift file
Figure 12-11. Creating the GuessInputViewController.swift file
Now let’s create and connect the actions and outlets in the GuessInputViewController class, as shown in Listing 12-8.
Note To see the bound rectangles around your controls in your storyboard, as shown in Figure 12-11, select Editor Canvas Show Bounds Rectangle.
Figure 12-12. Creating the segue that transitions scenes when the Guess Random Number button is tapped
Figure 12-13. Creating the segue identifier
Note Make sure you press Return when you type the segue identifier. Xcode may not pick up the property change if you don’t press Return.
Now you need to write the code to handle the segue. In the ViewController class, add the code in Listing 12-9.
When the user taps the Guess Random Number button, the segue gets called, and the function prepareForSegue gets called. You first check to see whether it was the MyGuessSegue segue. You then populate the vc variable with the GuessInputViewController.
Lines 27 and 28 pass the previousGuess number and delegate to the GuessInputViewController.
How It Works
Here is how the code works:
Summary
This chapter covered why multiple inheritance is not used in Swift and how protocols and delegates work. When you think of delegates, think of helper classes. When your class conforms to a protocol, the delegate’s functions help your class.
You should be familiar with the following terms:
Exercise