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

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

    Here is my take at it.

    As this is an enum and not a class, you have to think different(TM): it is your description that has to change when the "state" of your enum changes (as pointed out by @hu-qiang).

    enum SimpleEnumeration: ExampleProtocol {
      case Basic, Adjusted
    
      var description: String {
        switch self {
        case .Basic:
          return "A simple Enumeration"
        case .Adjusted:
          return "A simple Enumeration [adjusted]"
        }
      }
    
      mutating func adjust()  {
        self = .Adjusted
      }
    }
    
    var c = SimpleEnumeration.Basic
    c.description
    c.adjust()
    c.description
    

    Hope that helps.

提交回复
热议问题