Swift4语法极简手册 — Extensions

Swift4语法极简手册

第二十一章节:Extensions

Extensions

Extensions可以为已有的Classe,Structure,Enumeration或Protocol添加新的function

  • 可以添加computed instnace properties以及computed type properties
  • 可以添加instance methodstype methods
  • 可以提供新的init初始化方法
  • 可以定义subscript
  • 可以定义netsted types
  • 可以实现protocol

Extensions只能添加新的,你不能在Extensions中override已有的方法

定义一个Extension

1
2
3
extension SomeType : SomeProtocol{
}

添加computed Properties

1
2
3
4
5
6
7
8
9
10
11
12
13
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
print("One inch is \(oneInch) meters")
// Prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// Prints "Three feet is 0.914399970739201 meters"

添加Init

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
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))

添加Methods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
3.repetitions {
print("Hello!")
}
// Hello!
// Hello!
// Hello!

添加Mutating Instance Methods

1
2
3
4
5
6
7
extension Int {
mutating func square() {
self = self * self
}
}
var someInt = 3
someInt.square()

添加Subscript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
extension Int {
subscript(digitIndex: Int) -> Int {
var decimalBase = 1
for _ in 0..<digitIndex {
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7

添加Nested Type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
extension Int {
enum Kind {
case negative, zero, positive
}
var kind: Kind {
switch self {
case 0:
return .zero
case let x where x > 0:
return .positive
default:
return .negative
}
}
}