【问题标题】:Use reduce to combine int from class使用 reduce 从类中组​​合 int
【发布时间】:2018-10-06 07:28:25
【问题描述】:

我看过这里:Swift 3 - Reduce a collection of objects by an Int property 和这里:https://medium.com/@abhimuralidharan/higher-order-functions-in-swift-filter-map-reduce-flatmap-1837646a63e8,但我无法减少工作。编辑:也许是因为他们改变了代码在 swift 4 中的编译方式(我正在使用)https://stackoverflow.com/a/46432554/7715250

这是因为我收到此错误:

上下文闭包类型 '(_, Test) -> _' 需要 2 个参数,但在闭包体中使用了 1 个

这是我的课:

class Test {
    let amountLeftToDownload: Int
    let amountDownloaded: Int

    init(amountLeftToDownload: Int, amountDownloaded: Int) {
        self.amountLeftToDownload = amountLeftToDownload
        self.amountDownloaded = amountDownloaded
    }
}

我有一个数组(进度)。我想获取下载总数,即每个测试实例的 amountLeftToDownload + amountDownloaded。我试过这个:

let totalDownloadsToProcess = progress.reduce(0) {$0.amountLeftToDownload, $0.amountDownloaded }

我将逗号替换为 + 和其他一些东西,但它不起作用。

【问题讨论】:

    标签: swift


    【解决方案1】:

    传递给reduce 的闭包有两个参数:第一个是累加器,第二个是要归约的数组中的一个元素。因此,您需要将当前记录中的值添加到当前总计中:

    let totalDownloadsToProcess = progress.reduce(0) { $0 + $1.amountLeftToDownload + $1.amountDownloaded }
    

    如果你命名输入可能会更清楚:

    let totalDownloadsToProcess = progress.reduce(0) { totalSoFar, elem in totalSoFar + elem.amountLeftToDownload + elem.amountDownloaded }
    

    为数组中的每个元素调用闭包。在每一步,它都会返回一个新值,当处理下一个元素时,该值会以totalSoFar 的形式传入。在处理第一个元素时,0 用作totalSoFar 的初始值。

    【讨论】:

    • 啊,我想我现在明白了:)我会尽快接受
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2022-11-24
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多