码迷,mamicode.com
首页 > 编程语言 > 详细

Swift -- enum 继承 protocol

时间:2015-12-04 00:44:00      阅读:879      评论:0      收藏:0      [点我收藏+]

标签:

原文地址链接:http://blog.csdn.net/duanyipeng/article/details/32338575

Apple官方文档:The Swift Programming Language
Protocols and Extensions一节的小节练习,要求自行定义一个enumeration枚举类型,并且遵循ExampleProtocol协议:

  

  1. protocol ExampleProtocol {  
  2.     var simpleDescription: String { get }  
  3.      mutating func adjust()  
  4. }  

  // 枚举继承协议

  1. enum EnumConformToProtocol: ExampleProtocol {  
  2.     case First(String), Second(String), Third(String)  
  3.       
  4.     var simpleDescription: String {  
  5.         get {  
  6.             switch self {  
  7.             case let .First(text):  
  8.                 return text  
  9.             case let .Second(text):  
  10.                 return text  
  11.             case let .Third(text):  
  12.                 return text  
  13.             default:  
  14.                 return "get error"  
  15.             }  
  16.         }  
  17.         set {  
  18.             switch self {  
  19.             case let .First(text):  
  20.                 self = .First(newValue)  
  21.             case let .Second(text):  
  22.                 self = .Second(newValue)  
  23.             case let .Third(text):  
  24.                 self = .Third(newValue)  
  25.             }  
  26.         }  
  27.     }  
  28.     mutating func adjust() {  
  29.         switch self {  
  30.         case let .First(text):  
  31.             self = .First(text + " (first case adjusted)")  
  32.         case let .Second(text):  
  33.             self = .Second(text + " (second case adjusted)")  
  34.         case let .Third(text):  
  35.             self = .Third(text + " (third case adjusted)")  
  36.         }  
  37.     }  
  38. }  
  39. var enumConformToProtocolTest = EnumConformToProtocol.First("FirstVal")  
  40. enumConformToProtocolTest.simpleDescription  
  41. enumConformToProtocolTest.adjust()  
  42. enumConformToProtocolTest.simpleDescription  
  43.   
  44. enumConformToProtocolTest = EnumConformToProtocol.Third("ThirdVal")  
  45. enumConformToProtocolTest.simpleDescription  
  46. enumConformToProtocolTest.adjust()  
  47. enumConformToProtocolTest.simpleDescription  
  48.   
  49. var e = EnumConformToProtocol.Second("Hello")  
  50. var text = e.simpleDescription  
  51. e.simpleDescription = "Adios"  
  52. text = e.simpleDescription  
  53. e.adjust()  
  54. text = e.simpleDescription

Swift -- enum 继承 protocol

标签:

原文地址:http://www.cnblogs.com/lianfu/p/5018003.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!