Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift 4 Protocol-Oriented Programming

You're reading from   Swift 4 Protocol-Oriented Programming Bring predictability, performance, and productivity to your Swift applications

Arrow left icon
Product type Paperback
Published in Oct 2017
Publisher Packt
ISBN-13 9781788470032
Length 210 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (9) Chapters Close

Preface 1. Starting with the Protocol FREE CHAPTER 2. Our Type Choices 3. Extensions 4. Generics 5. Object-Oriented Programming 6. Protocol-Oriented Programming 7. Adopting Design Patterns in Swift 8. Case Studies

Delegation

Delegation is used extensively within the Cocoa and Cocoa Touch frameworks. The delegation pattern is a very simple but powerful pattern where an instance of one type acts on behalf of another instance. The instance that is doing the delegating keeps a reference to the delegate instance, and then, when an action happens, the delegating instance calls the delegate, to perform the intended function. Sounds confusing? It really isn't.

This design pattern is implemented in Swift by creating a protocol that defines the delegates' responsibilities. The type that conforms to the protocol, known as the delegate, will adopt this protocol, guaranteeing that it will provide the functionality defined by the protocol.

For the example in this section, we will have a structure named Person. This structure will contain two properties of the String type, named firstName and lastName. It will also have a third property that will store the delegate instance. When either the firstName or lastName properties are set, we will call a method in the delegate instance that will display the full name. Since the Person structure is delegating the responsibility for displaying the name to another instance, it does not need to know or care how the name is being displayed. Therefore, the full name could be displayed in a console window or in a UILabel; alternatively, the message may be ignored altogether.

Let's start off by looking at the protocol that defines the delegate's responsibilities. We will name this delegate DisplayNameDelegate:

protocol DisplayNameDelegate {  
  func displayName(name: String) 
} 

In the DisplayNameDelegate protocol, we define one method that the delegate needs to implement named displayName(). It is assumed that within this method the delegate will somehow display the name; however, it is not required. The only requirement is that the delegate implements this method.

Now let's look at the Person structure that uses the delegate:

struct Person { 
  var displayNameDelegate: DisplayNameDelegate 
 
  var firstName = "" {  
    didSet { 
      displayNameDelegate.displayName(name: getFullName()) 
    } 
  } 
  var lastName = "" {  
    didSet { 
      displayNameDelegate.displayName(name: getFullName()) 
    } 
  } 
 
  init(displayNameDelegate: DisplayNameDelegate) {  
    self.displayNameDelegate = displayNameDelegate 
  } 
 
  func getFullName() -> String {  
    return "\(firstName) \(lastName)" 
  } 
} 

In the Person structure, we start off by adding the three properties, which are named displayNameDelegate, firstName, and lastName. The displayNameDelegate property contains an instance of the delegate type. This instance will be responsible for displaying the full name when the values of the firstName and lastName properties change.

Within the definitions for the firstName and lastName properties, we define the property observers. The property observers are called each time the value of the properties is changed. Within these property observers, is where we call the displayName() method of our delegate instance to display the full name.

Now let's create a type that will conform to the DisplayNameDelegate protocol. We will name this type MyDisplayNameDelegate:

struct MyDisplayNameDelegate: DisplayNameDelegate {  
  func displayName(name: String) { 
    print("Name: \(name)") 
  } 
} 

In this example, all we will do is print the name to the console. Now let's see how we would use this delegate:

var displayDelegate = MyDisplayNameDelegate() 
var person = Person(displayNameDelegate: displayDelegate) 
person.firstName = "Jon" 
person.lastName = "Hoffman" 

In this code, we begin by creating an instance of the MyDisplayNameDelegate type and then use that instance to create an instance of the Person type. Now when we set the properties of the Person instance, the delegate is used to print the full name to the console.

While printing the name to the console may not seem that exciting, the real power of the delegation pattern comes when our application wants to change the behavior. Maybe in our application we will want to send the name to a web service or display it somewhere on the screen or even ignore the change. To change this behavior, we simple need to create a new type that conforms to the DisplayNameDelegate protocol. We can then use this new type when we create an instance of the Person type.

Another advantage that we get from using the delegation pattern is loose coupling. In our example, we separated the logic part of our code from the view by using the delegate to display the name whenever the properties changed. Loose coupling promotes a separation of responsibility, where each type is responsible for very specific tasks; this makes it very easy to swap out these tasks when requirements change, because we all know that requirements change often.

So far in this chapter, we have looked at protocols from a coding point of view, now let's look at protocols from a design point of view.

You have been reading a chapter from
Swift 4 Protocol-Oriented Programming - Third Edition
Published in: Oct 2017
Publisher: Packt
ISBN-13: 9781788470032
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime