Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Associated types


An associated type declares a placeholder name that can be used instead of a type within a protocol. The actual type to be used is not specified until the protocol is adopted. While creating generic functions and types, we used a very similar syntax. Defining associated types for a protocol is very different. We specify an associated type using the typealias keyword.

Let's see how to use associated types when we define a protocol. In this example, we will define the QueueProtocol protocol that will define the capabilities that need to be implemented by a queue that implements it:

protocol QueueProtocol {
    typealias 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 used this associated type twice within the protocol, once as the parameter type for the addItem() method, and once when we defined the return type of the getItem...