Protocols
protocol
定义了完成特定任务所需的method/properties/其他要求protocol
中没有实际的implementation- 可以被
class
,structure
,enumeration
使用 - 满足protocol要求的type被称为“conform to that protocol”
- 相当于Java的interface,但java的interface可以有default implementation
protocol Driveable{
func turnLeft()
func turnRight()
func brake()
//By default, methods are required, unless:
@objc optional func reverse()
}
class Car : Driveable{
}
//Can adopt more than 1 protocol:
class Bicycle : Driveable, TwoWheels{
}
//If the class has a superclass:
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
// class definition goes here
}
Delegation
一个类比:
- Protocol: 职位要求
- Delegator:老板
- Delegate:实习生小王
老板 (delegator) 把ios开发的任务 (event) 交给实习生小王 (delegate) 完成,因为他知道小王的条件符合职位要求 (conforms to protocol)
Closures
- 类似于c和objective-c中的blocks,其他编程语言中的lambdas
- 函数是closures
//Closures: A block of functionality / code
func backward(_ s1:Stirng, _ s2: String) -> Bool{
return s1 > s2
}
let names = ["Brett", "Eddy", "Hilary", "Sophie", "Ray"]
names.sort(by: backward)
//General Form
names.sort(by: {(s1:Stirng, s2: String) Bool in
return s1 > s2
})
//First Shortcut: delete type
names.sort(by: {(s1, s2) in
return s1 > s2
})
//Second Shortcut: remove return keyword
names.sort(by: {(s1, s2) in s1 > s2})
//Third Shortcut: use implied variable name
names.sort(by: {$0 > $1})
//Fourth Shortcut: if closure is the last argument, can remove argument label (trailing closures)
names.sort{$0 > $1}