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

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


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.Basec.adjust()let cDescription = c.simpleDescription


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.Basicc.descriptionc.adjust()c.description

Hope that helps.


Here's another approach, using only the knowledge gained from the tour until that point*

enum SimpleEnumeration: String, ExampleProtocol {    case Basic = "A simple enumeration", Adjusted = "A simple enumeration (adjusted)"    var simpleDescription: String {        get {            return self.toRaw()        }    }    mutating func adjust() {        self = .Adjusted    }}var c = SimpleEnumeration.Basicc.adjust()let cDescription = c.simpleDescription

If you want to have adjust() act as a toggle (although there's nothing to suggest this is the case), use:

mutating func adjust() {    switch self {    case .Basic:        self = .Adjusted    default:        self = .Basic    }}

*(Although it doesn't explicitly mention how to specify a return type and a protocol)