You have a protocol that defines methods and possibly properties that an implementation type should provide. Some of these methods / properties use or return objects of a different type to a type that implements the protocol. So, for example, if you have a protocol that defines certain types of collections of objects, you can define a related type that defines the elements of a collection.
So, let's say I want the protocol to define Stack, but what kind of stack? It doesn't matter, I just use the associated type to act as the owner of the place.
protocol Stack
{
// typealias Element - Swift 1
associatedtype Element // Swift 2+
func push(x: Element)
func pop() -> Element?
}
In the above Elementthere is a type of any objects in the stack. When I implement a stack, I use typealiasto indicate the specific type of stack elements.
class StackOfInt: Stack
{
typealias Element = Int
var ints: [Int] = []
func push(x: Int)
{
ints.append(x)
}
func pop() -> Int?
{
var ret: Int?
if ints.count > 0
{
ret = ints.last
ints.removeLast()
}
return ret
}
}
, , Stack, , Element Int. , , typealias, Element . push() Element == Int.