我尝试在Swift中使用reduce函数。
taken = basket.reduce(into: 0) { (initial, bi) in
initial + bi.amount() - bi.discount()
}
Run Code Online (Sandbox Code Playgroud)
但是我得到一个错误: Result of operator '-' is unused.
有两种类似的reduce方法:
func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result
Run Code Online (Sandbox Code Playgroud)
闭包更新累加器,但不返回值,而在
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
Run Code Online (Sandbox Code Playgroud)
闭合返回更新的累积值。
在你的情况下应该是
taken = basket.reduce(into: 0) { (initial, bi) in
// Update accumulated value:
initial += bi.amount() - bi.discount()
}
Run Code Online (Sandbox Code Playgroud)
使用第一个版本,或
taken = basket.reduce(0) { (initial, bi) in
// Compute and return accumulated value:
return initial + bi.amount() - bi.discount()
}
Run Code Online (Sandbox Code Playgroud)
使用第二个版本。
| 归档时间: |
|
| 查看次数: |
349 次 |
| 最近记录: |