1.完整的定义一个closure
var addClosure : (Int,Int) ->Int = {
(a:Int,b:Int)
in
return a + b
}
省略参数类型
addClosure = { a,b in return a + b}
单语句closure可以省略return
addClosure = { a,b in a + b}
终极简化,将参数用$1,$2的形式简化
addClosure = { $0 + $1 }
2.closure入参,并与函数相比较
func excute(a:Int,_ b:Int,operation:(Int,Int)->Int) -> Int {
return operation(a,b)
}
func multi(a:Int,_ b:Int) -> Int{
return a * b
}
//closure入参
excute(1, 2, operation: addClosure)
//函数入参
excute(1, 2, operation: multi)
closure 匿名入参
excute(1, 2, operation: {a,b in a + b})
closure 匿名入参 简化
excute(1, 2, operation: { $0 + $1 })
closure 匿名入参,如果closure参数在最后一个,则可以将closure写在函数的参数列表的外边
excute(1, 2) { (a, b) -> Int in
a + b
}
excute(1, 2) { $0 + $1 }
3.如果closure没有返回值,则必须标明Void 而不能像函数一样省略
let addClosure2 : (Int,Int) -> Void = {
print($0 + $1)
}
4.捕获变量,closure可以捕获变量
func counting() -> () ->Int {
var count = 0 ;
let incrementCount : ()->Int = {
count += 1
return count
}
return incrementCount;
}
var c1 = counting()
c1() //1
c1() //2
c1() //3
var c2 = counting()
c2() //1
c2() //2
c2() //3
其实func也可以
func counting2() -> () ->Int {
var count = 0 ;
func incrementCount() ->Int {
count += 1
return count
}
return incrementCount;
}
var c21 = counting2()
c21() //1
c21() //2
c21() //3
var c22 = counting2()
c22() //1
c22() //2
c22() //3
5.closure和函数相比
- closure就是一个没有名字的函数
- closure可以没有名字
- closure不能省略Void