# 闭包(closures)
-/*闭包(Closures)
- *闭包是自包含的功能代码块,可以在代码中使用或者用来作为参数传值。
- *在Swift中的闭包与C、OC中的blocks和其它编程语言(如Python)中的lambdas类似。
- *闭包可以捕获和存储上下文中定义的的任何常量和变量的引用。这就是所谓的变量和变量的自封闭,
- *因此命名为”闭包“("Closures)").Swift还会处理所有捕获的引用的内存管理。
- *
- *全局函数和嵌套函数其实就是特殊的闭包。
- *闭包的形式有:
- *(1)全局函数都是闭包,有名字但不能捕获任何值。
- *(2)嵌套函数都是闭包,且有名字,也能捕获封闭函数内的值。
- *(3)闭包表达式都是无名闭包,使用轻量级语法,可以根据上下文环境捕获值。
- *
- * Swift中的闭包有很多优化的地方:
- * (1)根据上下文推断参数和返回值类型
- * (2)从单行表达式闭包中隐式返回(也就是闭包体只有一行代码,可以省略return)
- * (3)可以使用简化参数名,如$0, $1(从0开始,表示第i个参数...)
- * (4)提供了尾随闭包语法(Trailing closure syntax)
- */
// MARK: -
// MARK: 闭包
import UIKit
var arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({(a:Int,b:Int) -> Bool in
return a > b
})
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({a,b in return a>b})
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({a,b in a>b})
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({$0 > $1})
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace(>)
var 字母数组 = ["a","aaa","abc","b","a","ss","aass"]
字母数组.sortInPlace({ (s1 : String, s2 : String) -> Bool in
if (s1.characters.count != s2.characters.count) {
return s1.characters.count < s2.characters.count
} else {
return s1 < s2
}
})
字母数组
字母数组 = ["a","aaa","abc","b","a","ss","aass"]
字母数组.sortInPlace({
if ($0.characters.count != $1.characters.count) {
return $0.characters.count < $1.characters.count
} else {
return $0 < $1
}
})
//trailing closure
字母数组 = ["a","aaa","abc","b","a","ss","aass"]
字母数组.sortInPlace(){ (s1 : String, s2 : String) -> Bool in
if (s1.characters.count != s2.characters.count) {
return s1.characters.count < s2.characters.count
} else {
return s1 < s2
}
}
字母数组
//captures Values
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({fabs(Float($0 - 5)) > fabs(Float($1 - 5))})
let num = 5
arr = [2,3,5,1,2,5,10,2,5]
arr.sortInPlace({fabs(Float($0 - num)) > fabs(Float($1 - num))})
func calcTotalMiles(todayMiles : Int) -> ()->Int {
var totalMiles = 0
return {totalMiles += todayMiles; return totalMiles;}
}
//twoMiles实际上是闭包,闭包是引用类型的,所以totalMiles已经被闭包所引用,它的值会一直保留在闭包里面而不会为0
let twoMiles = calcTotalMiles(2)
twoMiles()
twoMiles()
let myPlan = twoMiles
myPlan()
twoMiles()
//typealias定义一个闭包closure
//相当于typedef void (^GetNumBlcok)(int num);
typealias GetNumClosure = (num:Int) -> Void
var myClosure : GetNumClosure?
func getNum(closure : (num:Int) -> Void) {
myClosure = closure
}
getNum { (num) -> Void in
//输出调用的值
num
}
myClosure!(num : 5)
myClosure!(num : 4)