-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Mastering Swift 5.3
By :

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. When creating generic functions and types, we used a very similar syntax, as we have seen throughout this chapter. 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, which defines the capabilities that need to be implemented by the queue that implements it:
protocol QueueProtocol {
associatedtype QueueType
mutating func add(item: QueueType)
mutating func getItem() -> QueueType?
func count() -> Int
}
In this protocol, we defined one associated type, named QueueType
. We then used this associated type twice within the protocol: once as the parameter...