简单例子 1
func add = (function () {
var counter = 0;
return func sun() {return counter += 1;}
})();
add();
add();
add();
// 计数器为 3
例子2
func makeIncrementor(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementor() -> Int {
runningTotal += amount
return runningTotal
}
return incrementor
}
let incrementByTen = makeIncrementor(forIncrement: 10)
// 返回的值为10
incrementByTen()
// 返回的值为20
incrementByTen()
// 返回的值为30
incrementByTen()
// 返回的值为40
incrementByTen()
let alsoIncrementByTen = incrementByTen
// 返回的值也为50
print(alsoIncrementByTen())
例子3
// 普通函数
func operaShow(flag: Bool) -> (int1: Int,int2: Int) -> Int {
func a(int1: Int, int2: Int){
return int1 + int2
}
func b(int1: Int, int2: Int){
return int1 - int2
}
return flag ? a:b
}
// 闭包
func operaShow(flag: Bool) -> (int1: Int,int2: Int) -> Int {
func flag?{(int1: Int, int2: Int) -> Int in
return int1 + int2
}:{(int1: Int, int2: Int) -> Int in
return int1 - int2
{
}
operaShow(flag:true)(5,4)
operaShow(flag:false)(5,4)
网友评论