我尝试在Swift中使用reduce函数。
taken = basket.reduce(into: 0) { (initial, bi) in
initial + bi.amount() - bi.discount()
}
但是我遇到了错误:Result of operator '-' is unused.
答案 0 :(得分:3)
有两种类似的reduce
方法:In
func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result
闭包更新累加器,但不返回值,而在
中func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
闭包返回更新的累积值。
您的情况应该是
taken = basket.reduce(into: 0) { (initial, bi) in
// Update accumulated value:
initial += bi.amount() - bi.discount()
}
使用第一个版本,或
taken = basket.reduce(0) { (initial, bi) in
// Compute and return accumulated value:
return initial + bi.amount() - bi.discount()
}
使用第二个版本。