这篇博文来源于一段代码中的操作符+做了参数,由于本人接触ios还不到3个月,网上搜索不到相关的解释,被迫只有自己分析问题了,希望能帮助到有相关问题的朋友
extension Array {
func accumulate<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) -> Result) -> [Result] {
var running = initialResult
return map {
running = nextPartialResult(running, $0)
return running
}
}
func filter(_ isIncluded: (Element) -> Bool) -> [Element] {
var result: [Element] = []
for x in self where isIncluded(x) {
result.append(x)
}
return result
}
}
let c1 = [1,2,3,4].accumulate(0, +)//输出[1,3,6,10]
let c2 = [1,2,3,4].accumulate(0, {a,b in return a + b})//输出[1,3,6,10]
操作符+到底完成了什么功能呢,带着疑惑我查找开发者文档发现Numeric,该协议中有一个方法
static func +(lhs: Self, rhs: Self) -> Self
之后又想到swift中的闭包和其他编程语言的匿名函数比较类似,那么不能发现操作符+其实就是完成了一个函数的功能
那么可以想到把+换成自己定义的具有类似功能的函数是否能完成同样的功能呢?
func add(num1: Int, num2: Int) -> Int{
return num1 + num2
}
let c3 = [1,2,3,4].accumulate(0, add)