100 Days of Swift - Day 07 - 闭包Closures part 2
6.6 有参闭包作为函数参数
func travel(action: (String) -> Void) {
print("I'm getting ready to go.")
// 4. 函数体调用闭包
action("London")
print("I arrived!")
}
let parameterBlock = { (place: String) in
// 5. 执行闭包,使用闭包传入的参数
print("I'm going to \(place) in my car")
}
travel(action: parameterBlock)
I'm getting ready to go.
I'm going to London in my car
I arrived!
6.7 有返回值闭包作为函数参数
func travel(action: (String) -> String) {
print("I'm getting ready to go.")
// 4. 调用闭包使用参数,并接收闭包返回值
let description = action("London")
print(description)
print("I arrived!")
}
let returnValueBlock = { (place: String) -> String in
// 5. 执行闭包,使用闭包传入的参数,并返回一个数据
return "I'm going to \(place) in my car"
}
travel(action: returnValueBlock)
6.8 简化闭包
func travel(action: (String) -> String) {
print("I'm getting ready to go.")
// 3. 调用闭包使用参数,并接收闭包返回值
let description = action("London")
print(description)
print("I arrived!")
}
travel { (place: String) -> String in
return "I'm going to \(place) in my car"
}
travel { place -> String in
return "I'm going to \(place) in my car"
}
- short hand 省略闭包参数类型、省略返回值类型
travel { place in
return "I'm going to \(place) in my car"
}
- short hand 省略闭包参数类型、省略返回值类型、省略返回值关键字
travel { place in
"I'm going to \(place) in my car"
}
- short hand 省略闭包参数类型、省略返回值类型、省略返回值关键字、省略闭包参数 使用$0 代替参数
travel {
"I'm going to \($0) in my car"
}
I'm getting ready to go.
I'm going to London in my car
I arrived!
I'm getting ready to go.
I'm going to London in my car
I arrived!
I'm getting ready to go.
I'm going to London in my car
I arrived!
I'm getting ready to go.
I'm going to London in my car
I arrived!
I'm getting ready to go.
I'm going to London in my car
I arrived!
- 简写闭包目的在于让代码可读性增强,如果一个闭包有超过三个以上的参数,还是建议不要简写,因为简写之后反而让代码不易阅读。
6.9 多参数闭包
func travel(action: (String, Int) -> String) {
print("I'm getting ready to go.")
let description = action("London", 60)
print(description)
print("I arrived!")
}
travel {
"I'm going to \($0) at \($1) miles per hour."
}
- 闭包参数和函数参数类似,可以有多个但不是越多越好,建议不要超过三个,但不绝对。因为一般参数过多的函数就需要考虑重构。
6.10 闭包作为函数返回值
- 闭包可以作为函数参数,也可以作为函数返回值。
- 定义有参函数,函数返回值为有参有闭包
func travel() -> (String) -> Void {
return {
print("I'm going to \($0)")
}
}
let result = travel()
result("London")
travel()("London")
6.11 闭包捕获外部变量
func travel() -> (String) -> Void {
var counter = 1
return {
print("\(counter). I'm going to \($0)")
counter += 1
}
}
let result = travel()
result("London")
result("London")
result("London")
1. I'm going to London
2. I'm going to London
3. I'm going to London
- 闭包捕获外部变量实际是为了保证闭包安全执行,延长了外部变量的声明周期保证闭包调用时外部变量生命周期与闭包统在。
6.12 小结
- 闭包可以作为变量,函数参数,函数返回值使用
- 闭包和函数类似,可以设置参数,在闭包体内使用,也可以返回数据
- 如果闭包作为函数最后一个参数称之为尾随闭包可以简写
- Swift允许闭包可以简写参数及返回值
- 闭包捕获外部变量将延长其生命周期直至闭包销毁