【问题标题】:Custom object reduce values for similar key in swift自定义对象在swift中减少类似键的值
【发布时间】:2020-10-29 16:57:55
【问题描述】:

我使用[GeneralCategory] ​​形式的fetchRequest 核心数据模型对象中的Dictionary(grouping:by) 创建了一个唯一键字典。现在我想找出一种方法来减少 Dictionary 值中的特定参数(在这种情况下,我已将布尔值转换为双精度值)。

struct GeneralCategory {
    var drank: Bool?
    var dateOnly: String?
    var otherParam1
    var otherParam2
    etc
}

let groupedDict = Dictionary(grouping: coreDataFetch) { ($0.dateOnly!) }.reduce(into: [String: Double]()) { $0[$1.key] = Double($1.1.count) }

// returns the reduced parameter across all keys, not per key

我将如何减少 per 键的值,以便从


[["7-7-20": 1.0, 0.0, 1.0],["7-8-20": 0.0, 1.0], ["7-9-20": 0.0, 1.0, 0.0 ,1.0]]

to 

[["7-7-20": 2.0],["7-8-20": 1.0], ["7-9-20": 2.0]]

提前感谢您的任何建议,我希望我的问题很清楚(第一篇文章)。

【问题讨论】:

  • 您提供的示例实际上与您提出的要求不符。请澄清。
  • 你所说的 是什么意思(在这种情况下是我已转换为双精度的布尔值?你是如何将 Bool 转换为 Double 的。你的需求不够明确。
  • 抱歉,bool 值衡量一个人是否喝酒,我有一个计数器,每次发生的情况都会增加 += 1。为了应用 reduce 闭包,我必须将 bool 值转换为 double。但是感谢您在 7 秒内回复,这令人印象深刻。

标签: arrays swift dictionary functional-programming reduce


【解决方案1】:

使用 mapValues(_:)reduce(_:_:) 可以获得预期的结果。

reduce(_:_:) 中,您只需检查drank 是否为true 并相应地增加计数器。

let groupedDict = Dictionary(grouping: coreDataFetch) { $0.dateOnly }.mapValues {
    $0.reduce(0.0) { (result, category) -> Double in
        if let drank = category.drank, drank {
            return result + 1.0
        }
        return result
    }
}

注意:我看不出有任何理由在这里使用Double。您可以改用Int 类型。

【讨论】:

  • 太棒了。如果答案有帮助,请接受(在左侧打勾)。编码愉快..?
  • 你打赌。 Double 值也是 Charts 库 BarChartDataEntry (Double: Double) 的要求,因为我使用数据来填充 Barnhart。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多