閉包的特點(diǎn):一個(gè)函數(shù)有權(quán)訪問(wèn)另外一個(gè)函數(shù)內(nèi)的變量和參數(shù)
- 閉包—匿名函數(shù)
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
})
//逐步簡(jiǎn)化
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} //結(jié)尾閉包
arr.sorted(by: {$0 > $1})
arr.sorted(by: >)
- 結(jié)尾閉包
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
- 內(nèi)容捕獲
var arr: [Int] = []
for _ in 1..<10 {
arr.append(Int(arc4random() % 10))
}
arr.sorted { (a, b) -> Bool in
return a > b
}
// 外部可變參數(shù)可以在閉包內(nèi)部使用
var num = 5
arr.sorted { (a, b) -> Bool in
return abs(a-num) > abs(b-num)
}
- 閉包和函數(shù)是引用類型
//按值傳遞::意味著當(dāng)將一個(gè)參數(shù)傳遞給一個(gè)函數(shù)時(shí)仓洼,函數(shù)接收的是原始值的一個(gè)副本。因此,如果函數(shù)修改了該參數(shù),僅改變副本,而原始值保持不變山林。
//按引用傳遞:意味著當(dāng)將一個(gè)參數(shù)傳遞給一個(gè)函數(shù)時(shí),函數(shù)接收的是原始值的內(nèi)存地址,而不是值的副本澳厢。因此,如果函數(shù)修改了該參數(shù)囚似,調(diào)用代碼中的原始值也隨之改變剩拢。
func runningWithMetersPerDay(metersPerDay: Int) -> ()->Int {
var totalMeters = 0
//返回一個(gè)閉包(函數(shù))
return {
totalMeters += metersPerDay
return totalMeters
}
}
let planA = runningWithMetersPerDay(metersPerDay: 100)
planA() //100
planA() //200
let anotherPlan = planA
anotherPlan() //300
anotherPlan() //400
planA() //500 (值改變了,按引用傳遞)