7. Closures, Extensions, Protocols, Delegation, and ScrollView - 笔记

[weak self] 比[unowned self]更安全。

拓展:分割代码快,更简洁,不要滥用

协议:是一个更简洁表达API的方式。是一种类型: 协议用在属性/方法的参数或返回值中。

下面是协议的一个例子:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
protocol Moveable {
mutating func moveTo(p: CGPoint)
}

class Car: Moveable {
func moveTo(p: CGPoint) {
print("Car move to \(p)")
}

func changeOil() {
print("changeOil")
}

var name: String

init() {
self.name = ""
}

init(name: String) {
self.name = name
}

}

struct Shape: Moveable {
mutating func moveTo(p: CGPoint) {
print("Shape move to \(p)")
}

func draw() {

print("draw")
}
}

let prius: Car = Car(name: "A")
let square: Shape = Shape()

var thingToMove: Moveable = prius
thingToMove.moveTo(CGPoint(x: 100, y: 100))
var find: Car = prius
find.name

// 协议可以作为一个类型,来存储实现该协议的变量,但是不能直接调用后者的非协议的方法和属性
//thingToMove.changeOil()
thingToMove = square

let thingsToMove: [Moveable] = [prius, square]

func slide(var slider: Moveable) {
let positionToSlideTo = CGPoint(x: 88, y: 88)
slider.moveTo(positionToSlideTo)
}

slide(prius)
slide(square)

protocol Slippery {
var speed: Double { get }
}

extension Car: Slippery {
var speed: Double {
return 1
}
}

func slipAndSlide(x: protocol<Slippery, Moveable>) {
print("slipAndSlide")
}
slipAndSlide(prius)