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

Typical Swift inheritance

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.
Understanding Protocols
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
Protocol Definition
Protocol Listed After Superclass
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
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.
Protocol Definitions
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

Guessing game app home view

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
- 1.Create a new Swift project based on the Single View App template, name it RandomNumberDelegate, and save it, as shown in Figure 12-5.Figure 12-5.
Creating the project
- 2.From the Document Outline, select the Main.storyboard, and then select the View Controller Scene. Then select Editor ➤ Embed In ➤ Navigation Controller. This embeds your View Controller in a Navigation Controller and enables you to easily transition back and forth between other View Controllers, as shown in Figure 12-6.Figure 12-6.
Embedding the View Controller in a Navigation Controller
- 3.In the View Controller, add two Label objects and two Button objects along with their four respective outlets to control the view, as shown in Figure 12-7. (Be sure to embed the labels and buttons in a horizontally and vertically center-aligned stack view like you did in Chapter 10.)Figure 12-7.
Outlets necessary to control the view
- 4.
Next, connect the Action in Listing 12-4 to the playAgainButton.
IBAction Function
- 5.
Add the code in Listing 12-5 for the functions to handle when the user guesses a number and to handle creating a random number.
User Guess Delegate Function and createRandomNumber Function
- 6.
Declare and initialize the two variables on lines 12 and 13 in Listing 12-6.
Variable Declarations and Initializations
- 7.
Modify the function viewDidLoad() to handle how the view should look when it first appears and create the random number to guess, as shown in Listing 12-7.
viewDidLoad Function
- 8.Now you need to create a view to enable the users to enter their guesses. In the Main.storyboard file, drag a new View Controller next to the home View Controller and add a Label, a Text Field, and a Button in another center-aligned stack view. For the Text Field object, in the Placeholder property, type “Number between 0-100”, as shown in Figure 12-8.Figure 12-8.
Creating the Guess View Controller and objects
- 9.You next need to create a class for the Guess Input View Controller. Create a Swift file and save it as GuessInputViewController.swift by selecting File ➤ New ➤ File. Then choose iOS and Cocoa Touch Class and name the class GuessInputViewController as a subclass of UIViewController, as shown in Figure 12-9.Figure 12-9.
Creating the GuessInputViewController.swift file
- 10.Let’s associate the GuessInputViewController class with the Guess View Controller created in Step 8. From the Main.storyboard file, select the Guess Input View Controller, select the Identity Inspector, and select or type GuessInputViewController in the Class field, as shown in Figure 12-10.Figure 12-10.
Setting the Guess Input View Controller class
Class Listing
- 11.You are almost done. You need to connect the scene with a segue. A segue enables you to transition from one scene to another. Control-drag from the Guess Random Number button to the Guess Input View Controller and select Show as the type of Action Segue, as shown in Figure 12-11.Figure 12-11.
Creating the segue that transitions scenes when the Guess Random Number button is tapped
- 12.Now you need to give the segue an identifier. Click the segue arrow, select the Attributes Inspector, and name the segue MyGuessSegue, as shown in Figure 12-12.Figure 12-12.
Creating the segue identifier
Note
Make sure you press Return or Tab after you type the segue identifier. Xcode may not recognize the property change if you don’t press Return.
prepareForSegue Method
When the user taps the Guess Random Number button, the segue gets called, and the method prepareForSegue gets called. You first check to see whether it was the MyGuessSegue segue. You then populate the vc variable with the GuessInputViewController.
- 13.
If you haven’t added the GuessDelegate delegate to the ViewController class, do it now, as shown in Listing 12-10.
ViewController Class with GuessDelegate Listed
How It Works
When the user taps the Guess Random Number link, prepareForSegue is called. See line 75 in Listing 12-9.
Because the ViewController conforms to the GuessDelegate (see line 11 in Listing 12-10), you can pass self to the delegate in GuessInputViewController.
The GuessInputViewController scene is displayed.
When the user guesses a number and taps Save Guess, the saveGuess method is called (see line 33 in Listing 12-8).
Since you passed ViewController as the delegate, it can pass the guess back to the ViewController.swift file via the userDidFinish method (see line 35 in Listing 12-8).
Now you can determine whether the user guessed the correct answer and pop the GuessInputViewController view from the stack (see line 55 in Listing 12-5).
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.
Multiple inheritance
Protocols
Delegates
Exercises
Change the random number the computer guesses from 0–100 to 0–50.
In the main scene, display how many guesses the user has made trying to guess the random number.
In the main scene, display how many games the user has played.