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

前端 未结 15 1307
终归单人心
终归单人心 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 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.Basic
    c.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)

提交回复
热议问题