操作员的结果-未使用迅速减少

Evg*_*ban 3 reduce swift

我尝试在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.

Mar*_*n R 5

有两种类似的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)

使用第二个版本。