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: Int) -> T? mutating func delete(at index: Int) }
We start the List
protocol by defining the associated type T
. This associated type will be the type of data stored in the list. We use the T
type as the parameter for the add...