I try to use reduce function in Swift.
taken = basket.reduce(into: 0) { (initial, bi) in
initial + bi.amount() - bi.discount()
}
However i got an error: Result of operator '-' is unused.
There are two similar reduce
methods: In
func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result
the closure updates the accumulator, but does not return a value, whereas in
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
the closure returns the updated accumulated value.
In your case it should be
taken = basket.reduce(into: 0) { (initial, bi) in
// Update accumulated value:
initial += bi.amount() - bi.discount()
}
using the first version, or
taken = basket.reduce(0) { (initial, bi) in
// Compute and return accumulated value:
return initial + bi.amount() - bi.discount()
}
using the second version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With