iOS,object-c和swift开发Swift编程Swifty Coding

Swift 函数式学习-链式调用

2016-07-31  本文已影响111人  小黑Swift

一般函数调用

        //0.一般函数调用
        var someClosure = {
            (param: String) in
            print(param)
        }       
        someClosure("call some closure")
        // = "call some closure"

链式调用

        //1.链式调用-返回值是函数,并且函数的返回值是调用者本身,可以构成链式调用
        class Home {
            typealias SELF = Home
            var run1:(String) -> SELF {
                return {
                    print($0)
                    return self
                }
            }
            
            var run2:(String) -> SELF {
                return {
                    print($0)
                    return self
                }
            }
            
            func runrun() {
                run1("1").run2("2")
            }
        }
        
        Home().runrun() 
         =  /* 
            1
            2
              */

        struct MyFactory {
            var result = 0
            mutating func calculate(closure:(Int) -> Int) -> MyFactory {
                result = closure(result)
                return self
            }
        }
        
        class ViewController {
            
            func myClick()  {
                var calc = MyFactory()
                let result = calc.calculate {
                    var rs = $0 + 10
                    rs *= 10
                    return rs
                    }.result
                print(result)
            }
        }
        
        ViewController().myClick() // = 100
主要流向

参考资料来源:http://valiantcat.com/

上一篇下一篇

猜你喜欢

热点阅读