a protocol with an enum in swift

main.swift
// Define a protocol with an associated enum
protocol Vehicle {
    var type: VehicleType { get }
    func start()
}

enum VehicleType {
    case car(String)
    case motorcycle(String)
    case bike(String)
}

// Conform to the protocol and implement the methods
struct Honda: Vehicle {
    let type: VehicleType
    
    func start() {
        switch type {
        case .car(let model):
            print("Starting \(model) car")
        case .motorcycle(let model):
            print("Starting \(model) motorcycle")
        case .bike(let model):
            print("Starting \(model) bike")
        }
    }
}

// Create an instance and call the method
let honda = Honda(type: .car("CR-V"))
honda.start()
// Output: Starting CR-V car
737 chars
33 lines

In the above code example, we define a protocol named Vehicle with an associated enum named VehicleType. The VehicleType enum has three cases representing different types of vehicles, each with an associated string value.

We then create a struct named Honda that conforms to the Vehicle protocol and implements the required method start(). The implementation of start() includes a switch statement that performs a different action based on the VehicleType of the Honda instance.

Finally, we create an instance of Honda with the type of .car("CR-V") and call the start() method. The output of the program prints "Starting CR-V car", which is the result of the car case in the VehicleType enum.

gistlibby LogSnag