//閉包的幾種書寫方式 var names = [13,345,2,323,1,8,21,42,34,32,42,1] // 1 func compares(args: Int, args2: Int) ->Bool { return args > args2 } var names2 = names.sort(compares) print(names2) // 2 names2 = names.sort({(args: Int, args2: Int) -> Bool in return args < args2 }) print(names2) // 3 names2 = names.sort({$0 > $1}) print(names2) func customer_fn(cu_fn: ()-> String) { let str: String = cu_fn() print("customer accpect args for closure : \(str)") } customer_fn({" this is closeure "}) //autoclosure func customer_fn(@autoclosure cu_fn: ()-> String) { let str: String = cu_fn() print("customer accpect args for closure : \(str)") } customer_fn(" this is closeure2 ") //4 此種狀況比較特殊,只適用於一句表達式,作比較操做,纔可用 names2 = names.sort(>) print(names2) //尾隨閉包 //使用場景:須要傳入一個閉包,而且爲最後一個參數時 names2 = names.sort() { $0 > $1} print(names2) //使用場景: 須要傳入一個閉包,有且只有一個參數時 names2 = names.sort {$0 <= $1} print(names2) // 閉包捕獲上下文變量,並在生命週期內存儲變量值,常例: 嵌套函數種 func makeIncrementer(forIncrement amount: Int) -> () -> Int { var runningTotal = 0 func incrementer() -> Int { runningTotal += amount return runningTotal } return incrementer } let increment_fn = makeIncrementer(forIncrement: 10) print(increment_fn()) print(increment_fn())