使用protocol
关键字声明协议。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
类、枚举和结构体都能够响应协议。
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
试验
定义一个枚举类型并响应上面的协议
声明结构体SimpleStructure
时使用的mutating
关键字标记会对结构体进行修改的方法。由于类中的方法总是可以修改类的对象,因此不需要在SimpleClass
中进行标明。
Swift使用extension
关键字给一个已经存在的类型添加功能。你可以给任何地方声明的类型使用扩展,使得它响应某个协议,不管它是从框架还是其它地方导入的。
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
7.simpleDescription
试验
给Double
类型使用扩展添加一个absoluteValue
属性。
可以像其它数据类型一样用协议来声明变量或这常量,例如创建一个对象的集合,使得它可以容纳可以响应同一个协议的不同数据类型的值。当你使用这些值的时候,不能调用协议以外的方法。
let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
//protocolVAlue.anotherProperty //Uncomment to see the error
尽管protocolValue
变量是SimpleClass
的对象,但是编译器把它当成是ExampleProtocol
类型。这就意味着你只能访问协议里定义的方法和属性。