参考:
Swift高阶函数:Map,Filter,Reduce等-Part 1
闭包产生过程:
第一步
函数参数
//平方计算
func square(a: Float) -> Float {
return a*a
}
//立方计算
func cube(a: Float) -> Float {
return a*a*a
}
func averageOfFunction(a: Float,b: Float,f:((Float) -> Float)) -> Float {
return (f(a) + f(b))/2
}
let one = averageOfFunction(a: 3, b: 4, f: square(a:))
let two = averageOfFunction(a: 3, b: 4, f: cube(a:))
averageOfFunction函数包含3个参数:a,b类型为浮点型数,f的类型为函数(函数的参数为一个浮点型数,返回值为一个浮点型数)
第二步
使用闭包来替代其中的函数参数
let three = averageOfFunction(a: 3, b: 4, f: {(x: Float) -> Float in return x*x*x})
print(three)
闭包的最外层使用大括号,原先的函数实现部分的大括号用in来替代
第三步
简化:省略闭包内参数类型的声明和返回值声明
编译器能够推断出averageOfFunction期望传入作为参数的函数需要接收一个float值,然后返回另一个float值
let four = averageOfFunction(a: 3, b: 4, f: {x in return x*x})
print(four)
第四步
简化:省略return语句
let five = averageOfFunction(a: 3, b: 4, f: {x in x*x})
print(five)
第五步
简化:使用默认参数名$0
let six = averageOfFunction(a: 3, b: 4, f: {$0 * $0})
print(six)
练习
let mapArray = [1,7,4,8,2]
func add1(a: Int) -> String {
return "\(a)个"
}
func newArr(a: [Int]) -> [String] {
var new = [String]()
for b in a {
new.append("\(b)个")
}
return new
}
let mapArray2 = newArr(a: mapArray)
func newArr2(a: [Int],f: ((Int) -> String)) -> [String] {
var new = [String]()
for b in a {
new.append(f(b))
}
return new
}
let mapArray3 = newArr2(a: mapArray, f: add1(a:))
let mapArray4 = newArr2(a: mapArray, f: {(b: Int) -> String in return "\(b)个"})
print(mapArray4)
let mapArray5 = newArr2(a: mapArray, f: {b in return "\(b)个"})
print(mapArray5)
let mapArray6 = newArr2(a: mapArray, f: {b in "\(b)个"})
print(mapArray6)
let mapArray7 = newArr2(a: mapArray, f: {"\($0)个"})
print(mapArray7)