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

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

    This is my attempt:

    protocol ExampleProtocol {
        var simpleDescription: String { get }
        mutating func adjust()
    }
    
    enum ExampleEnum : ExampleProtocol {
        case Base, Adjusted
    
        var simpleDescription: String {
            return self.getDescription()
        }
    
        func getDescription() -> String {
            switch self {
            case .Base:
                return "A simple description of enum"
            case .Adjusted:
                return "Adjusted description of enum"
            }
        }
    
        mutating func adjust() {
            self = ExampleEnum.Adjusted
        }
    }
    
    var c = ExampleEnum.Base
    c.adjust()
    let cDescription = c.simpleDescription
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-22 17:31

    My first contribution here:

    enum SimpleEnum: ExampleProtocol {
        case Basic(String), Adjusted(String)
        init() {
            self = SimpleEnum.Basic("A simple Enum")
    
        }
    
        var simpleDescription: String {
            get {
                switch self {
                case let .Basic(string):
                    return string
                case let .Adjusted(string):
                    return string
                }
            }
        }
    
        mutating func adjust() {
            self = SimpleEnum.Adjusted("full adjusted")
    
        }
    }
    
    var c = SimpleEnum()
    c.adjust()
    let cDescription = c.simpleDescription
    

    Thanks for others!

    0 讨论(0)
提交回复
热议问题