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 have 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: Int) -> T? mutating func delete(at index: Int) }
We start the List...