协议和扩展

使用protocol来声明一个协议。javascript

protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }

类、枚举和结构体均可以实现协议。java

class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription

练习: 写一个实现这个协议的枚举。nginx

注意声明SimpleStructure时候mutating关键字用来标记一个会修改结构体的方法。SimpleClass的声明不须要标记任何方法,由于类中的方法一般能够修改类属性(类的性质)。swift

使用extension来为现有的类型添加功能,好比新的方法和计算属性。你能够使用扩展在别处修改定义,甚至是从外部库或者框架引入的一个类型,使得这个类型遵循某个协议。框架

extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } print(7.simpleDescription)

练习: 给Double类型写一个扩展,添加absoluteValue功能。spa

你能够像使用其余命名类型同样使用协议名——例如,建立一个有不一样类型可是都实现一个协议的对象集合。当你处理类型是协议的值时,协议外定义的方法不可用。code

let protocolValue: ExampleProtocol = a print(protocolValue.simpleDescription) // print(protocolValue.anotherProperty) // Uncomment to see the error

即便protocolValue变量运行时的类型是simpleClass,编译器会把它的类型当作ExampleProtocol。这表示你不能调用类在它实现的协议以外实现的方法或者属性。对象

相关文章
相关标签/搜索