Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result of operator - is unused swift reduce

Tags:

swift

reduce

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.

like image 227
Evgeniy Kleban Avatar asked Jan 27 '23 19:01

Evgeniy Kleban


1 Answers

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.

like image 98
Martin R Avatar answered Feb 09 '23 04:02

Martin R