Reader small image

You're reading from  Swift Protocol-Oriented Programming - Fourth Edition

Product typeBook
Published inJun 2019
Reading LevelIntermediate
Publisher
ISBN-139781789349023
Edition4th Edition
Languages
Tools
Right arrow
Author (1)
Jon Hoffman
Jon Hoffman
author image
Jon Hoffman

Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon the challenges that the field of information technology provides and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon’s other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter Kara is currently working towards her black belt.
Read more about Jon Hoffman

Right arrow

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 don't 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 we can use associated types within a protocol. In this example, we will illustrate the Queue protocol, which will define the requirements that are 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. First, we use it as the parameter type for the addItem() method, and then we 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 you 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 look at how to use protocols to implement the delegation design pattern.

Previous PageNext Page
You have been reading a chapter from
Swift Protocol-Oriented Programming - Fourth Edition
Published in: Jun 2019Publisher: ISBN-13: 9781789349023
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.
undefined
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 $15.99/month. Cancel anytime

Author (1)

author image
Jon Hoffman

Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon the challenges that the field of information technology provides and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon’s other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter Kara is currently working towards her black belt.
Read more about Jon Hoffman