在Swift

时间:2016-03-19 03:21:27

标签: swift dictionary reduce

我正在尝试计算字典中的元素。字典的类型为[EKCalendar:ReminderList],其中ReminderList是具有list属性的类。我想浏览字典并加上所有这些列表的计数。

我的字典位于属性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
}

4 个答案:

答案 0 :(得分:2)

let count = reminderListsStructure.structure.reduce(0) { $0 + $1.1.list.count }

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

答案 1 :(得分:2)

我认为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{$0}.count //15

答案 2 :(得分:1)

当您reduce字典时,元素类型是Key和Value类型的元组,因此您可以使用:

dictionary.reduce(0) { $0 + $1.1.list.count }

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

dictionary.values.reduce(0) { $0 + $1.list.count }

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

答案 3 :(得分:0)

更简单明了的方式就是这样,

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
})