闭包的基本语法
var arr:[Int] = []
for _ in 0..<100{
arr.append(random()%1000)
}
//闭包作为函数的变量传入函数
arr.sort({ (a:Int , b:Int) -> Bool in
return a > b
})
//闭包语法的简化
arr.sort({(a:Int , b:Int)->Bool in return a > b})
arr.sort({a , b in return a > b})
arr.sort({a , b in a > b})
arr.sort({$0 > $1})
arr.sort(>)
//Trailing Closure结尾闭包
arr.sort(){a , b in
return a > b
}
arr.map{ (var number) -> String in
var res = ""
repeat{
res = String(number%2) + res
number /= 2
}while number != 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
rectangle.backgroundColor = UIColor.redColor()
showView.addSubview(rectangle)
UIView.animateWithDuration(2.0, animations: {
rectangle.backgroundColor = UIColor.blackColor()
rectangle.frame = showView.frame
})
闭包的内容捕获
var arr:[Int] = []
for _ in 0..<100{
arr.append(random()%1000)
}
arr.sort{ a, b in
abs(a-300) < abs(b-300)
}
var num = 700
arr.sort{a, b in
abs(a-num) < abs(b-num)
}
闭包和函数的引用类型
func runningMetersWithMetersPerDay( metersPerDay: Int) -> () -> Int{
var totalMeters = 0
return{
totalMeters += metersPerDay
return totalMeters
}
}
var playA = runningMetersWithMetersPerDay(2000)
playA()//2000
playA()//4000
playA()//6000
var playB = runningMetersWithMetersPerDay(5000)
playB()//5000
playB()//10000
var anotherPlay = playB//给原有的变量起了另外一个名字,调用那一个都会改变他们的值,这就说明闭包和函数是引用类型
anotherPlay()//15000
playB()//20000
let playC = runningMetersWithMetersPerDay(3000)//对于引用类型来讲,常量的概念不代表它里面的值不能被修改,实际代表的是playC这个名称是固定的
playC()//3000
playC()//6000
网友评论