swift 中相似键的自定义对象减少值
Custom object reduce values for similar key in swift
我使用 [GeneralCategory] 形式的 fetchRequest 核心数据模型对象中的 Dictionary(grouping:by) 创建了一个唯一键字典。现在我想找出一种方法来减少 Dictionary 值中的特定参数(在本例中是我已转换为双精度的布尔值)。
struct GeneralCategory {
var drank: Bool?
var dateOnly: String?
var otherParam1
var otherParam2
etc
}
let groupedDict = Dictionary(grouping: coreDataFetch) { ([=11=].dateOnly!) }.reduce(into: [String: Double]()) { [=11=][.key] = Double(.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]]
在此先感谢您的任何建议,希望我在问题中说清楚(首先 post)。
使用mapValues(_:)
和reduce(_:_:)
得到预期的结果。
在 reduce(_:_:)
中,您只需检查 drank
是否为 true
并相应地增加计数器。
let groupedDict = Dictionary(grouping: coreDataFetch) { [=10=].dateOnly }.mapValues {
[=10=].reduce(0.0) { (result, category) -> Double in
if let drank = category.drank, drank {
return result + 1.0
}
return result
}
}
注意: 我看不出有任何理由在这里使用 Double
。您可以改用 Int
类型。
我使用 [GeneralCategory] 形式的 fetchRequest 核心数据模型对象中的 Dictionary(grouping:by) 创建了一个唯一键字典。现在我想找出一种方法来减少 Dictionary 值中的特定参数(在本例中是我已转换为双精度的布尔值)。
struct GeneralCategory {
var drank: Bool?
var dateOnly: String?
var otherParam1
var otherParam2
etc
}
let groupedDict = Dictionary(grouping: coreDataFetch) { ([=11=].dateOnly!) }.reduce(into: [String: Double]()) { [=11=][.key] = Double(.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]]
在此先感谢您的任何建议,希望我在问题中说清楚(首先 post)。
使用mapValues(_:)
和reduce(_:_:)
得到预期的结果。
在 reduce(_:_:)
中,您只需检查 drank
是否为 true
并相应地增加计数器。
let groupedDict = Dictionary(grouping: coreDataFetch) { [=10=].dateOnly }.mapValues {
[=10=].reduce(0.0) { (result, category) -> Double in
if let drank = category.drank, drank {
return result + 1.0
}
return result
}
}
注意: 我看不出有任何理由在这里使用 Double
。您可以改用 Int
类型。