How to make an enum conform to a protocol in Swift?

前端 未结 15 1293
终归单人心
终归单人心 2020-12-22 16:32

Swift documentation says that classes, structs, and enums can all conform to protocols, and I can get to a point where they all conform. But I can

15条回答
  •  庸人自扰
    2020-12-22 17:12

    Here's building on Jack's answer:

    protocol ICanWalk {
        var description: String { get }
        mutating func stepIt()
    }
    
    enum TwoStepsForwardThreeStepsBack: Int, ICanWalk {
        case Base = 0, Step1, Step2
    
        var description: String {
            return "Step \(self.rawValue)"
        }
    
        mutating func stepIt() {
            if let nextStep = TwoStepsForwardThreeStepsBack( rawValue: self.rawValue + 1 ) {
                // going forward.
                self = nextStep
            } else {
                // back to the base.
                self = TwoStepsForwardThreeStepsBack.Base
            }
        }
    }
    

提交回复
热议问题