Generics in a protocol-oriented design

Now that we have seen how to use generics, let's see how we can use them in a protocol-oriented design. In a previous example in this chapter, we created a generic List type, however, we can greatly improve on this design by using what we learned throughout this chapter. We will include only a small subset of the actual requirements for a List type so we can focus on the design rather than all the requirements.

With a protocol-oriented design, we always start with the protocol. The following code shows the List protocol:

protocol List {  associatedtype T  subscript<E: Sequence>(indices: E) -> [T]      where E.Iterator.Element == Int { get }  mutating func add(_ item: T)  func length() -> Int func get(at index: ...

Get Swift 4 Protocol-Oriented Programming - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.