语法
通用的语法
{(parameters) -> return type in statements }
e.g
let studname = { println("Welcome to Swift Closures") } studname()
输出
Welcome to Swift Closures
以下闭包接受两个参数并返回一个布尔值:
{(Int, Int) -> Bool in Statement1 Statement 2 --- Statement n }
e.g
let divide = {(val1: Int, val2: Int) -> Int in return val1 / val2 } let result = divide(200, 20) println (result)
输出
10
e.g
func ascend(s1: String, s2: String) -> Bool { return s1 > s2 } let stringcmp = ascend("swift", "great") println (stringcmp)
输出
true
e.g
let sum = {(no1: Int, no2: Int) -> Int in return no1 + no2 } let digits = sum(10, 20) println(digits)
输出
30
sorted比较e.g
let count = [5, 10, -6, 75, 20] var descending = sorted(count, { n1, n2 in n1 > n2 }) var ascending = sorted(count, { n1, n2 in n1 < n2 }) println(descending) println(ascending)
输出
[75, 20, 10, 5, -6] [-6, 5, 10, 20, 75]
已知类型的闭包
考虑两个数相加。我们知道相加后将返回整数数据类型。因此,已知类型的闭包声明
let sub = {(no1: Int, no2: Int) -> Int in return no1 - no2 } let digits = sub(10, 20) println(digits)
-10
声明简写参数名称作为闭包
Swift 自动提供简写参数名内联闭包, 可以使用由 $0,$1,$2 等等名称,指的是封闭的参数值。
var shorthand: (String, String) -> String shorthand = { $1 } println(shorthand("100", "200"))
200
Swift 方便用户来表示内嵌闭包为缩写参数名为:$0, $1, $2 --- $n.
闭包参数列表中被省略定义部分,当我们表示内部闭包表达式简写参数名。 根据函数类型简写参数名称将被导出。由于简写参数表达体所定义的 'in' 关键字被省略。
闭包作为操作函数
let numb = [98, -20, -30, 42, 18, 35] var sortedNumbers = numb.sorted({ (left: Int, right: Int) -> Bool in return left < right }) let asc = numb.sorted(<) println(asc)
[-30, -20, 18, 35, 42, 98]
闭包作为尾随包
reversed = sorted(names) { $0 > $1}
其中 {$0 > $1} 表示为外部(名称)声明尾随闭包。
import Foundation var letters = ["North", "East", "West", "South"] let twoletters = letters.map({ (state: String) -> String in return state.substringToIndex(advance(state.startIndex, 2)).uppercaseString }) let stletters = letters.map() { $0.substringToIndex(advance($0.startIndex, 2)).uppercaseString } println(stletters)
[NO, EA, WE, SO]
捕获值和引用类型
在闭包的帮助下 Swift 完成捕捉常量和变量的值。它还参考修改值,即使常量和变量在闭包体已经不存。
let decrem = calcDecrement(forDecrement: 18) decrem()
在这里,oneDecrement 和 递减变量都指向同一个内存块闭合参考。
func calcDecrement(forDecrement total: Int) -> () -> Int { var overallDecrement = 100 func decrementer() -> Int { overallDecrement -= total println(overallDecrement) return overallDecrement } return decrementer } let decrem = calcDecrement(forDecrement: 18) decrem() decrem() decrem()
82 64 46