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

前端 未结 15 1283
终归单人心
终归单人心 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:17

    Here's a solution that doesn't change the current enum value, but their instance values instead (just in case it is useful to anyone).

    enum ProtoEnumeration : ExampleProtocol {
        case One(String)
        case Two(String)
    
        var simpleDescription: String {
            get {
                switch self {
                case let .One(desc):
                    return desc
                case let .Two(desc):
                    return desc
                }
            }
        }
        mutating func adjust() {
            switch self {
            case let .One(desc):
                self = .One(desc + ", adjusted 1")
            case let .Two(desc):
                self = .Two(desc + ", adjusted 2")
            }
        }
    }
    
    var p = ProtoEnumeration.One("test")
    p.simpleDescription
    p.adjust()
    p.simpleDescription
    

提交回复
热议问题