扩展为现有的类、结构体、枚举类型、或协议添加了新功能。这也包括了为无访问权限的源代码扩展类型的能力(即所谓的逆向建模)
Swift中的扩展可以:
- 添加计算实例属性和计算类型属性;
- 定义实例方法和类型方法;
- 提供新初始化器;
- 定义下标;
- 定义和使用新内嵌类型;
- 使现有的类型遵循某协议
在Swift 中,你甚至可以扩展一个协议,以提供其要求的实现或添加符合类型的附加功能
扩展可以向一个类型添加
新的方法,但是不能重写已有的方法。
格式:
1. 用extension 关键字来声明扩展
extension SomeType {
// new functionality to add to SomeType goes here
}
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}