减少以计算 Swift 中字典中的元素

Reduce to count elements in a dictionary in Swift

我正在尝试计算字典中的元素。字典的类型为 [EKCalendar: ReminderList],其中 ReminderList 是 class 和列表 属性。我想通过字典并将所有这些列表的计数加起来。

我的字典在 属性 self?.reminderListsStructure.structure.

let numberOfElements = self?.reminderListsStructure.structure.reduce(0) {
    accumulator, nextValue in
    return accumulator.list.count + nextValue.list.count  
    // COMPILE ERROR: Type of expression is ambiguous without more context
}
let count = reminderListsStructure.structure.reduce(0) { [=10=] + .1.list.count }

像这样。虽然没有足够的信息,所以我不能 100% 确定它是否有效。

当你reduce一个字典时,元素类型是Key和Value类型的元组,所以你可以使用:

dictionary.reduce(0) { [=10=] + .1.list.count }

或者,您可以只从字典中获取值并减少:

dictionary.values.reduce(0) { [=11=] + .list.count }

请注意,由于 Dictionary.values returns 是一个惰性迭代器,因此使用它的成本并不高。

我觉得这里选择flatMap比较合适:

let input = [
    1: [1],
    2: [1, 2],
    3: [1, 2, 3],
    4: [1, 2, 3, 4],
    5: [1, 2, 3, 4, 5]
]

let output = input.values.flatMap{[=10=]}.count //15

更简单明了的方法是这样的,

var dict = ["x" : 1 , "y" : 2, "z" : 3]

let count = dict.reduce(0, { x, element  in

    //maybe here some condition
    //if(element.value > 1){return x}

    return x + 1
})