扩展 (Extensions)
向一个已有的类、结构体或枚举类型添加新功能,包括再没有获取源代码的情况下扩展类型的能力(逆向建模)
向一个已有的类、结构体或枚举类型添加新功能,包括再没有获取源代码的情况下扩展类型的能力(逆向建模)
1.语法
使用关键字 extensionextension SomeType {
// new functionality to add to SomeType goes here
}
一个扩展可以扩展一个已有的类型,使其能够适配一个或多个协议,此时接口的名字应该完全按照类或结构体的名字进行书写
extension SomeType: SomeProtocol, AnotherProtocol {
// implementation of protocol requirements goes here
}
2.计算型属性
扩展可向已有类型添加计算型实例属性和计算型类型属性extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
let aMarathon = 42.km + 195.m
println("A marathon is \(aMarathon) meters long")
// prints "A marathon is 42195.0 meters long"
3.构造器
扩展可向已有类型添加新的构造器。可以扩展其他类型,将自己定制的类型作为构造器参数,或者提供该类型原始没有提供的额外选项struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// centerRect's origin is (2.5, 2.5) and its size is (3.0, 3.0)
4.方法
扩展可以向已有类型添加新的实例方法和类型方法// 向Int添加repetitions方法,使用一个 ()->() 类型的简单参数,标明函数没有参数没有返回值,之后对任意整数调用该方法,多次执行某任务
extension Int {
func repetitions(task: () -> ()) {
for i in 0..self {
task()
}
}
}
3.repetitions({
println("Hello!")
})
// Hello!
// Hello!
// Hello!
// 使用trailing闭包调用
3.repetitions {
println("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!
4.1修改实例方法
通过扩展也可以修改实例本身的方法,结构体和枚举类型中修改self或其属性的方法必须将该方法标注为mutating,正如来自原始实现的修改方法一样extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()
// someInt is now 9
5.下标
扩展可以向一个已有类型添加新的下标// 向Int类型添加一个整型下标,下标[n]返回十进制数组从右向左数的第n个数字
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 1...digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7
746381295[9]
// returns 0, as if you had requested:
0746381295[9]
6.嵌套类型
扩展可以向已有的类、结构体和枚举添加新的嵌套类型// 向Character添加新的嵌套枚举Kind,表示特定字符的类型,添加一个新的计算实例属性kind,返回合适的Kind枚举成员
extension Character {
enum Kind {
case Vowel, Consonant, Other
}
var kind: Kind {
switch String(self).lowercaseString {
case "a", "e", "i", "o", "u":
return .Vowel
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
return .Consonant
default:
return .Other
}
}
}
func printLetterKinds(word: String) {
println("'\(word)' is made up of the following kinds of letters:")
for character in word {
switch character.kind {
case .Vowel:
print("vowel ")
case .Consonant:
print("consonant ")
case .Other:
print("other ")
}
}
print("\n")
}
printLetterKinds("Hello")
// 'Hello' is made up of the following kinds of letters:
// consonant vowel consonant consonant vowel