闭包的特点:一个函数有权访问另外一个函数内的变量和参数
- 闭包—匿名函数
var arr: [Int] = []
for _ in 0..<100 {
arr.append(Int(arc4random() % 100))
}
func biggerNumberFirst(a: Int, b: Int) -> Bool {
return a > b
}
arr.sorted(by: biggerNumberFirst)
//闭包
arr.sorted(by: {(a: Int, b: Int) -> Bool in
return a > b
})
//逐步简化
arr.sorted(by: {(a: Int, b: Int) -> Bool in return a > b})
arr.sorted(by: {a, b in return a > b})
arr.sorted(by: {a, b in a > b})
arr.sorted{a, b in a > b} //结尾闭包
arr.sorted(by: {$0 > $1})
arr.sorted(by: >)
- 结尾闭包
var arr: [Int] = []
for _ in 0..<10 {
arr.append(Int(arc4random() % 100))
}
arr.map{(number) -> String in
var res = ""
var temp = number
repeat{
res = String(number % 2) + res
temp /= 2
}while temp != 0
return res
}
- 衍生
let showView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
rectangle.center = showView.center
showView.backgroundColor = UIColor.yellow
rectangle.backgroundColor = UIColor.red
showView.addSubview(rectangle)
UIView.animate(withDuration: 1.0) {
rectangle.backgroundColor = UIColor.yellow
rectangle.frame = showView.frame
}
PlaygroundPage.current.liveView = showView
- 内容捕获
var arr: [Int] = []
for _ in 1..<10 {
arr.append(Int(arc4random() % 10))
}
arr.sorted { (a, b) -> Bool in
return a > b
}
// 外部可变参数可以在闭包内部使用
var num = 5
arr.sorted { (a, b) -> Bool in
return abs(a-num) > abs(b-num)
}
- 闭包和函数是引用类型
//按值传递::意味着当将一个参数传递给一个函数时,函数接收的是原始值的一个副本。因此,如果函数修改了该参数,仅改变副本,而原始值保持不变。
//按引用传递:意味着当将一个参数传递给一个函数时,函数接收的是原始值的内存地址,而不是值的副本。因此,如果函数修改了该参数,调用代码中的原始值也随之改变。
func runningWithMetersPerDay(metersPerDay: Int) -> ()->Int {
var totalMeters = 0
//返回一个闭包(函数)
return {
totalMeters += metersPerDay
return totalMeters
}
}
let planA = runningWithMetersPerDay(metersPerDay: 100)
planA() //100
planA() //200
let anotherPlan = planA
anotherPlan() //300
anotherPlan() //400
planA() //500 (值改变了,按引用传递)
网友评论