a protocol that implements a enum variable in swift

Here's an example of a protocol in Swift that includes an enum variable:

main.swift
// Define the protocol
protocol Transportation {
    var mode: Mode { get set }
    func start()
}

// Define an enum for transportation modes
enum Mode {
    case car
    case bus
    case train
}

// Adopt the protocol
class Car: Transportation {
    var mode: Mode = .car // Set the default mode to car
    
    func start() {
        print("Starting the car!")
    }
}

class Bus: Transportation {
    var mode: Mode = .bus // Set the default mode to bus
    
    func start() {
        print("Starting the bus!")
    }
}

class Train: Transportation {
    var mode: Mode = .train // Set the default mode to train
    
    func start() {
        print("Starting the train!")
    }
}
687 chars
38 lines

In this example, the Transportation protocol includes a variable called mode of type Mode. Classes that adopt the Transportation protocol must implement the mode variable and the start() method.

Each class that adopts the Transportation protocol can set a default mode using the enum values defined in the Mode enum.

gistlibby LogSnag