• No results found

Associated types with protocols

When defining a protocol, there are times when it is useful to define one or more associated types. An associated type gives us a placeholder name that we can use within the protocol in place of a type. The actual type to use for the associated type is not defined until the protocol is adopted. The associated type basically says: We do not know the exact type to use;

therefore, when a type adopts this protocol it will define it. As an example, if we were to define a

protocol for a queue, we would want the type that adopts the protocol to define the instance types that the queue contains rather than the protocol.

To define an associated type, we use the associatedtype keyword. Let's see how to use associated types within a protocol. In this example, we will illustrate the Queue protocol that will define the requirements needed to implement a queue:

protocol Queue {

associatedtype QueueType

mutating func addItem(item: QueueType) mutating func getItem() -> QueueType? func count() -> Int

}

In this protocol, we define one associated type named QueueType. We then use this associated type twice within the protocol. We use it first as the parameter type for the addItem() method. We then use it again when we define the return type of the getItem() method as an optional type.

Any type that implements the Queue protocol must specify the type to use for the

QueueType placeholder, and must also ensure that only items of that type are used where the protocol requires the QueueType placeholder.

Let's look at how to implement Queue in a non-generic class called IntQueue. This class will implement the Queue protocol using the integer type:

struct IntQueue: Queue { var items = [Int]()

mutating func addItem(item: Int) { items.append(item)

}

mutating func getItem() -> Int? { if items.count > 0 {

return items.remove(at: 0) }

else { return nil

}

func count() -> Int { return items.count }

}

As we can see in the IntQueue structure, we use the integer type for both the parameter type of the addItem() method and the return type of the getItem() method. In this example, we implemented the Queue protocol in a non-generic way. Generics in Swift allow us to define the type to use at runtime rather than compile time. We will show how to use associated types with generics in Chapter 4, Generics.

Now that we have explored protocols in some detail, let's look at how we can use them in the real world. In the next section, we will see how to use protocols to implement the delegation design pattern.

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.