Reduce to count elements in a dictionary in Swift

Viewed 2744

I'm trying to count the elements of my dictionary. The dictionary is of type [EKCalendar: ReminderList] where ReminderList is a class with a list property. I want to go through the dictionary and add up the count of all these lists.

My dictionary is in the property 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 Answers

More simple and clear way goes like this,

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