【Swift学习笔记00】——enumeration枚举类型遵循协议protocol

Apple官方文档: The Swift Programming Language
Protocols and Extensions一节的小节练习,要求自行定义一个enumeration枚举类型,并且遵循ExampleProtocol协议:
protocol ExampleProtocol {
    var simpleDescription: String { get }
     mutating func adjust()
}

在网上找了好久,都不知道怎样实现,最后参照一篇帖子( http://forums.macrumors.com/showthread.php?t=1740890),最终实现如下:
enum EnumConformToProtocol: ExampleProtocol {
    case First(String), Second(String), Third(String)
    
    var simpleDescription: String {
        get {
            switch self {
            case let .First(text):
                return text
            case let .Second(text):
                return text
            case let .Third(text):
                return text
            default:
                return "get error"
            }
        }
        set {
            switch self {
            case let .First(text):
                self = .First(newValue)
            case let .Second(text):
                self = .Second(newValue)
            case let .Third(text):
                self = .Third(newValue)
            }
        }
    }
    mutating func adjust() {
        switch self {
        case let .First(text):
            self = .First(text + " (first case adjusted)")
        case let .Second(text):
            self = .Second(text + " (second case adjusted)")
        case let .Third(text):
            self = .Third(text + " (third case adjusted)")
        }
    }
}

var enumConformToProtocolTest = EnumConformToProtocol.First("FirstVal")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.adjust()
enumConformToProtocolTest.simpleDescription

enumConformToProtocolTest = EnumConformToProtocol.Third("ThirdVal")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.adjust()
enumConformToProtocolTest.simpleDescription


var e = EnumConformToProtocol.Second("Hello")
var text = e.simpleDescription
e.simpleDescription = "Adios"
text = e.simpleDescription
e.adjust()
text = e.simpleDescription

运行结果截图:


转载于:https://www.cnblogs.com/sesexxoo/p/6189924.html

你可能感兴趣的:(【Swift学习笔记00】——enumeration枚举类型遵循协议protocol)