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

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

    I came up with this

    protocol ExampleProtocol {
        var simpleDescription: String { get }
        mutating func adjust()
    }
    
    enum Seat: ExampleProtocol {
        case WindowSeat, MiddleSeat, AisleSeat
    
        var simpleDescription : String {
            switch self {
            case .WindowSeat:
                return "Window Seat"
            case .MiddleSeat:
                return "Middle Seat"
            case .AisleSeat:
                return "Aisle Seat"
            }
        }
    
        mutating func adjust() {
            switch self {
            case .WindowSeat:
                self = .MiddleSeat
            case .MiddleSeat:
                self = . AisleSeat
            case .AisleSeat:
                self = .WindowSeat
            }
        }
    }
    
    var seat = Seat.MiddleSeat
    print(seat.simpleDescription) // Middle Seat
    seat.adjust()
    print(seat.simpleDescription) // Aisle Seat
    

提交回复
热议问题