print("Hello, Swift!")
//使用 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
print(aDescription)
print(bDescription)
//注意在 SimpleStructure 声明的时候,使用 mutating 关键字标记一个会修改结构体的方法。SimpleClass 的声明不需要方法标记,因为类中的方法经常会修改类。
//使用 extension 为现有的类型添加功能,比如添加一个计算属性的方法。你可以在任何地方使用 extension 来给任意类型添加协议,甚至是从外部库或者框架中导入的类型。
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
//你可以像使用其他命名类型一样,使用一个接口名称 :例如,创建一个有不同类型但是都实现同一个接口的对象集合。当你处理接口类型的值时,接口外定义的方法不可用。
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
// protocolValue.anotherProperty // Uncomment to see the error
//即使 protocolValue 变量在运行时的类型是 simpleClass,但是编译器会把它当做 ExampleProtocol 类型。这表示你不能调用实现此接口的类中的自有的方法或者属性。