Chapter    12

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.

9781484214893_Fig12-01.jpg

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.

9781484214893_Fig12-02.jpg

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.

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

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

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.

9781484214893_Fig12-03.jpg

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.

9781484214893_Fig12-04.jpg

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:

  1. Create a new Swift project based on the Single View Application template, name it RandomNumberDelegate, and save it, as shown in Figure 12-5.

    9781484214893_Fig12-05.jpg

    Figure 12-5. Creating the project

  2. Select the Main.storyboard file, and from the File Inspector, uncheck the Use Auto Layout option. Then click the Disable Size Classes button. This will enable you to focus on just one device, the iPhone, and not worry about Auto Layout, as shown in Figure 12-6.

    9781484214893_Fig12-06.jpg

    Figure 12-6. Turning off Auto Layout

  3. From the Document Outline, select View Controller. Then select Editor image Embed In image Navigation Controller. This embeds your scene in a Navigation Controller and enables you to easily transition back and forth to new scenes, as shown in Figure 12-7.

    9781484214893_Fig12-07.jpg

    Figure 12-7. Embedding the View Controller in a Navigation Controller

  4. In the View Controller, add two Label objects and two Button objects along with four Outlet objects, which will control the view, as shown in Figure 12-8 and Listing 12-4.

    9781484214893_Fig12-08.jpg

    Figure 12-8. Outlets necessary to control the view

  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.
  6. Declare and initialize the two variables on lines 13 and 14 in Listing 12-6.
  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.
  8. Now you need to create a view to enable the users to enter their guesses. In the Storyboard.swift file, drag a new View Controller next to the home View Controller and create a label, a text field, and a button. For the Text Field object, in the Placeholder property, type Number between 0-100, as shown in Figure 12-9.

    9781484214893_Fig12-09.jpg

    Figure 12-9. Create the Guess View Controller and objects

  9. You need to create a class for the Guess Input View Controller. Create a Swift file and save it as GuessInputViewController.swift. Select File image New image File. Then choose iOS image Source image Cocoa Touch Class and name the class GuessInputViewController. It’s subclassed from UIViewController, as shown in Figure 12-10.

    9781484214893_Fig12-10.jpg

    Figure 12-10. Create 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-11.

    9781484214893_Fig12-11.jpg

    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 image Canvas image Show Bounds Rectangle.

  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 push as the type of Action Segue, as shown in Figure 12-12.

    9781484214893_Fig12-12.jpg

    Figure 12-12. 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-13.

    9781484214893_Fig12-13.jpg

    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.

  13. Finally, if you haven’t added the GuessDelegate delegate to the ViewController class, do it now, as shown in Listing 12-10.

How It Works

Here is how the code works:

  • When the user taps the Guess Random Number link, prepareForSegue is called. See line 24 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 saveGuessAction is called (see line 40 in Listing 12-8).
  • Since you passed ViewController to the delegate, it can pass the guess back in the ViewController.swift file (see line 42 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 74 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.

You should be familiar with the following terms:

  • Multiple inheritance
  • Protocols
  • Delegates

Exercise

  • 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.
..................Content has been hidden....................

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