Swift 학습(3): 클로즈업(Closures)

8767 단어
정의
  (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
}

 
시스템에서 흔히 볼 수 있는 클립: 맵, 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

좋은 웹페이지 즐겨찾기