Swift
引入了一些高階函數(shù)券膀,比如map
适瓦、filter
、reduce
焙畔,今天簡(jiǎn)單介紹一下reduce
的用法.
reduce
用于做序列元素的累加掸读,如數(shù)組元素的累加。
/// initialResult: Result 初始值;
/// nextPartialResult:(Result, Int) 下一輪計(jì)算值儿惫, Result = initialResult + Int
/// Result是每輪計(jì)算的返回值(結(jié)果)澡罚, Int 是數(shù)組元素
/// -> Result 返回值
sortArr.reduce(initialResult: Result, nextPartialResult: (Result, Int) throws -> Result(Result, Int) throws -> Result>)
舉個(gè)例子
var aarray = [1, 2, 3, 4, 5, 6, 7, 8]
let reduceArr = aarray.reduce(0) { (result, item) -> Int in
print("result:\(result) item:\(item), \(result+item)")
return result + item
}
print("reduce:\(reduceArr)")
輸出結(jié)果
init:0 item:1, result:1
init:1 item:1, result:2
init:2 item:2, result:4
init:4 item:3, result:7
init:7 item:4, result:11
init:11 item:5, result:16
init:16 item:6, result:22
init:22 item:7, result:29
init:29 item:8, result:37
reduce:37
如果把初始值
換成100
, 結(jié)果是這樣的
var aarray = [1, 2, 3, 4, 5, 6, 7, 8]
let reduceArr = aarray.reduce(100) { (result, item) -> Int in
print("result:\(result) item:\(item), \(result+item)")
return result + item
}
print("reduce:\(reduceArr)")
輸出結(jié)果
init:100 item:1, result:101
init:101 item:1, result:102
init:102 item:2, result:104
init:104 item:3, result:107
init:107 item:4, result:111
init:111 item:5, result:116
init:116 item:6, result:122
init:122 item:7, result:129
init:129 item:8, result:137
reduce:137
如果有興趣肾请,自己敲幾行代碼驗(yàn)證一下吧_