协议和扩展
用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 SimpleStructture: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructture()
b.adjust()
let bDescription = b.simpleDescription
练习
写一个实习该接口的枚举
注意声明SimpleStructture的时候mutating关键字用来标记可以修改结构体的方法。SimpleClass的声明不需要标记任何方法因为类中的方法经常会修改类。
使用extension为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展给任何类型添加协议,甚至是你从外部库或者框架中导入的类型。
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
var t: Int = 6
t.adjust()
练习
给Double类型写一个扩展,添加absoluteValue功能。
你可以像使用其他命名类型一样使用协议名--例如,创建一个有不同类型但是都实现同一个接口。当你处理类型是协议的值时,接口的外部定义方法不可用。
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty) //Uncomment to see the error
即使protocolValue运行时的类型是SimpleClass,编译器会把他的类型当做ExampleProtocol。这意味着你不能调用类的属性和方法除非在协议中就有。
另外:发现github上已经有翻译好的了。链接 https://github.com/CocoaChina-editors/Welcome-to-Swift
我仍会继续翻译下去,做为自己学习的过程。