Swift 语言之闭包学习笔记

闭包表达式

闭包表达式语法:

1
2
3
4
5
6
7
8
9
10
11
12
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
var reversed = sorted(names, backwards)
// reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
reversed = sorted(names, { (s1: String, s2: String) -> Bool in
return s1 > s2
})

根据上下文推断类型:

1
reversed = sorted(names, { s1, s2 in return s1 > s2 } )

单行表达式闭包的隐式返回:

1
reversed = sorted(names, { s1, s2 in s1 > s2 } )

简写参数名:

1
reversed = sorted(names, { $0 > $1 } )

运算符函数:

1
reversed = sorted(names, >)

尾随闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
// here's how you call this function without using a trailing closure:
someFunctionThatTakesAClosure({
// closure's body goes here
})
// here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}

值捕获

1
2
3
4
5
6
7
8
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}

闭包是引用类型

1
2
3
4
5
6
7
8
9
10
11
12
13
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen()
// returns a value of 10
incrementByTen()
// returns a value of 20
incrementByTen()
// returns a value of 30
incrementByTen()
// returns a value of 40
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
// returns a value of 50
坚持原创技术分享,您的支持将鼓励我继续创作!