柯里化(Currying)
是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数
swift 面试可能会这样考吧, 叫你写一个加数字的返回一个新的结果
如: 加1 加2 加3 加4 普遍会写四个函数么?
那么用柯里化得方式写一个就OK了,它允许把上次的结果作为返回一个新的函数结果
func addOne(_ num: Int) -> Int {
return num + 1
}
func addTo(_ adder: Int) -> (Int) -> Int {
return {
num in
return num + adder
}
}
let addTwo = addTo(2) //返回的两次 int的函数
let result = addTwo(6) // result = 8
func greaterThan(_ comparer: Int) -> (Int) -> Bool {
return { $0 > comparer }
}
let greaterThan10 = greaterThan(10);
greaterThan10(13) // => true
greaterThan10(9) // => false
protocol TargetAction {
func performAction()
}
struct TargetActionWrapper<T: AnyObject>: TargetAction {
weak var target: T?
let action: (T) -> () -> ()
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
enum ControlEvent {
case touchUpInside
case valueChanged
// ...
}
class Control {
var actions = [ControlEvent: TargetAction]()
func setTarget<T: AnyObject>(_ target: T, action: @escaping (T) -> () -> (), controlEvent: ControlEvent) {
actions[controlEvent] = TargetActionWrapper(
target: target, action: action)
}
func removeTargetForControlEvent(_ controlEvent: ControlEvent) {
actions[controlEvent] = nil
}
func performActionForControlEvent(_ controlEvent: ControlEvent) {
actions[controlEvent]?.performAction()
}
}