O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, as we have seen throughout this chapter so far. Defining associated types for a protocol, however, is very different. We specify an associated type using the associatedtype 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 the queue that implements it:

 

protocol QueueProtocol { associatedtype QueueType mutating func add(item: QueueType) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required