Swift语法基础:6 - Swift的Protocol和Extensions

前端之家收集整理的这篇文章主要介绍了Swift语法基础:6 - Swift的Protocol和Extensions前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前面我们知道了枚举类型和结构体的声明,嵌套,以及基本的使用,现在让我们来看看Swift中的另外两个,一个是Protocol(协议),一个是Extensions(类别):


1.声明Protocol

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

PS: 在声明协议的时候,如果你要修改某个方法属性,你必须的在该方法加上mutating这个关键字,否则不能修改.


2.使用Protocol

  1. class SimpleClass: ExampleProtocol {
  2. var simpleDescription: String = "A very simple class."
  3. var anotherProperty: Int = 69105
  4. func adjust() {
  5. simpleDescription += " Now 100% adjusted."
  6. }
  7. }
  8. var a = SimpleClass()
  9.  
  10. a.adjust()
  11.  
  12. let aDescription = a.simpleDescription
  13. println(aDescription)
  14. // 打印出来的结果是: A very simple class. Now 100% adjusted.

同样的,在结构体里一样可以使用,但是必须的加上mutating:

  1. struct SimpleStructure:ExampleProtocol {
  2. var simpleDescription: String = "A simple structure."
  3. mutating func adjust() {
  4. simpleDescription += " (adjusted)"
  5. }
  6. }
  7.  
  8. var b = SimpleStructure()
  9. b.adjust()
  10. let bDescription = b.simpleDescription
  11. println(bDescription)
  12. // 打印出来的结果是: A simple structure. (adjusted)

Protocol也可以这么使用:

  1. let protocolValue:ExampleProtocol = a
  2. println(protocolValue.simpleDescription)
  3. // 打印出来的结果:A very simple class. Now 100% adjusted.

PS: 这里的a是前面例子里面的a.


3.声明Extensions

  1. extension Int: ExampleProtocol {
  2. var simpleDescription: String {
  3. return "The number \(self)"
  4. }
  5. mutating func adjust() {
  6. self += 42
  7. }
  8. }
  9. var ext = 7.simpleDescription
  10. println(ext)
  11. // 打印出来的结果: The number 7

好了,这次我们就讲到这里,下次我们继续~~

猜你在找的Swift相关文章