Swift学习(三):闭包(Closures)

定义

闭包(Closures)是独立的函数代码块,能在代码中传递及使用。

 

语法

{(parameters) -> return type in
  statements
}

注:闭包表达式语法可以使用常量参数、变量参数和 inout 类型作为参数,但皆不可提供默认值。

 

范例

func funA(var value : String,closure: (str : String) -> ()) {
    closure(str:value)
}

func closureA(var str : String){
    println("closureA : Hi , " + str)
}
func closureB(var str : String){
    println("closureB : Hi , " + str)
}


funA("cosmokey",closureA)    //closureA : Hi , cosmokey
funA("cosmokey",closureB)    //closureB : Hi , cosmokey
funA("cosmokey",{(var str : String) in println("closureC : Hi , " + str)})    //closureC : Hi , cosmokey

 

语法糖

根据上下文推断类型
funA("cosmokey",{str in println("closureD : Hi , " + str)})    //closureD : Hi , cosmokey

参数名简写
funA("cosmokey",{println("closureE : Hi , " + $0)})    //closureE : Hi , cosmokey

运算符函数
sort(names, >)  //sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } ) 

 

Trailing 闭包

注:Trailing 闭包是一个书写在函数括号之外(之后)的闭包表达式,函数支持将其作为最后一个参数调用。


funA("cosmokey"){
    str in println("closureF : Hi , " + str)     //closureF : Hi , cosmokey
}

 

系统常见闭包:map、filter和reduce

map

    map 可以把一个数组按照一定的规则转换成另一个数组

    定义

        func map<U>(transform: (T) -> U) -> U[]

    范例
        var oldArray = ["Ping","Cosmokey"]
        var newArray = oldArray.map(){"Hi , " + $0}    //["Hi , Ping","Hi , Cosmokey"]
filter

    filter 起到的就是筛选的功能,参数是一个用来判断是否筛除的筛选闭包

    定义
    
        func filter(includeElement: (T) -> Bool) -> [T]    

    范例

        var oldArray = ["Ping","Cosmokey","MM"]
        var newArray = oldArray.filter(){count($0) > 2}  //["Ping", "Cosmokey"]
reduce

    reduce 函数解决了把数组中的值整合到某个独立对象的问题。

    定义

        func reduce<U>(initial: U, combine: (U, T) -> U) -> U

    范例

        var oldArray = ["C","o","s","m","o","k","e","y"]
        var newArray = oldArray.reduce("Hi , "){
            var newValue = $0 + $1
            println(newValue)
            return newValue
        }
        /*
        Hi , C
        Hi , Co
        Hi , Cos
        Hi , Cosm
        Hi , Cosmo
        Hi , Cosmok
        Hi , Cosmoke
        Hi , Cosmokey
        */
        println(newArray)        //Hi , Cosmokey

 

你可能感兴趣的:(Swift学习(三):闭包(Closures))