原文地址链接: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
|
请发表评论