原文地址連結:http://blog.csdn.net/duanyipeng/article/details/32338575
Apple官方文件:The Swift Programming Language
Protocols and Extensions一節的小節練習,要求自行定義一個enumeration列舉型別,並且遵循ExampleProtocol協議:
- protocol ExampleProtocol {
- var simpleDescription: String { get }
- mutating func adjust()
- }
// 列舉繼承協議
- 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