# Swift 轻松掌握喵神高阶心法 I

2017-01-13 14:55:45来源:http://www.jianshu.com/p/f2b318da0a83作者:Doubles_Z人点击

Tip1 柯里化(Currying)

Swift 里可以将方法进行柯里化 (Currying)，这是也就是把接受多个参数的方法进行一些变形，使其更加灵活的方法。函数式的编程思想贯穿于 Swift 中，而函数的柯里化正是这门语言函数式特点的重要表现。

``func addOne(num: Int) -> Int {    return num + 1}``

``func addTo(_ adder: Int) -> (Int) -> Int {    return {         num in        return num + adder    }}``

``let addTwo = addTo(2) // addTwo: Int -> Intlet result = addTwo(6) // result = 8``

``func addTo(_ adder: Int) -> (Int) -> Intfunc addTo(_ adder: Int) -> ((Int) -> Int)``

``return {     num in    return num + adder}``

``let addTwo = addTo(2) //函数写法let addTwo = {(_ num) in return num + 2} //闭包写法let addTwo = {\$0 + 2} //简便写法``

``func greaterThan(_ comparer: Int) -> (Int) -> Bool {    return {\$0 > comparer}}let greaterThan10 = greaterThan(10)greaterThan10(13) // => truegreaterThan10(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()    }}``

``class View {    var backgroundColor = "default"     func changeColorToRed() {          backgroundColor = "red"    }}var view = View()var control = Control()control.setTarget(target: view/*泛型参数*/, action: view.changeColorToRed, controlEvent: .TouchUpInside)control.performActionForControlEvent(controlEvent: .TouchUpInside) //执行函数，修改字符串属性。``