So far in this chapter, we have seen how to use generics within types and functions. In this recipe, we will round off our journey through generics in Swift by looking at how they can be used in protocols. This will allow us to produce abstract interfaces while maintaining strongly typed requirements that allow for a more descriptive model.
In this recipe, we will build a model for a transport app in the UK with the goal of providing the distance and duration of a journey for different methods of transport.
How to do it...
The ways that people travel can be very different, so let's start by defining transport methods in a generic way, and then specify what those travel methods are:
- Define a protocol to define the features of a transport method:
protocol TransportMethod {
associatedtype CollectionPoint
var defaultCollectionPoint: CollectionPoint { get }
var averageSpeedInKPH: Double { get }
}
- Create a struct for traveling by train that...