下面是一个基本的闭包:
var multiplyClosure = { (a: Int, b: Int) -> Int in
return a * b
}
这就是一个基本的闭包类型,其基本格式为{ (参数列表)-> 返回值 in 函数体}
对上面这个闭包,可以进行如下的精减
1、去掉return
var multiplyClosure = { (a: Int, b: Int) -> Int in
a * b
}
2、去掉返回值类型,让系统自己推断
var multiplyClosure = { (a: Int, b: Int) in
a * b
}
3、将参数中的类型声明去掉,这种情况要实现声明变量的类型为闭包
var multiplyClosure: (Int,Int) -> Int
multiplyClosure = { (a, b) in
a * b
}
4、最后还可以将参数列表去掉,根据参数出现的位置来处理
var multiplyClosure: (Int,Int) -> Int
multiplyClosure = {
$0 * $1
}
声明一个没有参数和返回值的闭包
let voidClosure: () -> Void = {
print("Swift is awesome")
}
voidClosure()
下面这个是闭包作为返回值的一个例子
func countingClosure() -> (() -> Int) {
print("ok")
var counter = 0
let incrementCounter: () -> Int = {
print(counter)
counter += 1
print(counter)
return counter
}
return incrementCounter
}
let counter1 = countingClosure()
let counter2 = countingClosure()
//counter1时一个闭包,闭包作为函数执行,返回int类型的值
counter1()
counter1()
counter2()
一个例子:
func mathSum(times: Int, operation: (Int) -> Int) -> Int {
var result = 0
for i in 1...times {
result += operation(i)
}
return result
}
var result1 = mathSum(10, operation: {(a: Int) -> Int in return a * a })
print(result1)
var result2 = mathSum(10, operation: {(a: Int) -> Int in fibonacci(a)})
print(result2)