a protocol that implements an enum in swift

Here is an example of a protocol that defines an enum as an associated type:

main.swift
protocol Transportation {
    associatedtype VehicleType: RawRepresentable where VehicleType.RawValue == String
    var vehicleType: VehicleType { get }
    func start()
    func stop()
}

enum CarType: String {
    case sedan = "Sedan"
    case hatchback = "Hatchback"
    case SUV = "SUV"
}

struct Car: Transportation {
    var vehicleType: CarType
    
    func start() {
        print("The car with type \(vehicleType.rawValue) is started.")
    }
    
    func stop() {
        print("The car with type \(vehicleType.rawValue) is stopped.")
    }
}
555 chars
25 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