使用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类型。这就意味着你只能访问协议里定义的方法和属性。

本文介绍了Swift中协议与扩展的基本概念及应用方法。通过具体的类、结构体和枚举实例,展示了如何实现协议,并利用扩展增强现有类型的功能。
1162

被折叠的 条评论
为什么被折叠?



