Here is an example of a protocol that defines an enum as an associated type:
main.swift555 chars25 lines
In this example, the Transportation
protocol declares an associated type called VehicleType
which conforms to RawRepresentable
protocol where the RawValue
is a String
. The Car
struct conforms to the Transportation
protocol and specifies the associated type as CarType
. This allows us to use the vehicleType
property in the Car
struct and implement the required start
and stop
methods. Note that the CarType
enum is defined outside of the protocol, but it's used as a generic parameter through the associatedtype
keyword.
gistlibby LogSnag