Iterating along a Dictionary in Swift 3

Fabrizio Bartolomucci picture Fabrizio Bartolomucci · Jul 14, 2016 · Viewed 12k times · Source

I am trying to iterate along a Dictionary in order to prune unconfirmed entries. The Swift 3 translation of the following Objective-C code does not work:

[[self sharingDictionary] enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
                    SharingElement* element=[[self sharingDictionary] objectForKey:key];
                    if (!element.confirmed){
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [element deleteMe];
                        });
                        [[self sharingDictionary] performSelector:@selector(removeObjectForKey:) withObject:key
                                                       afterDelay:.2];
                    } else{
                        element.confirmed=NO;
                }];

And so I tried using the following compact enumerated() method in this way:

for (key, element) in self.sharingDictionary.enumerated(){
            if (!element.confirmed){
                    element.deleteMe()
                self.perform(#selector(self.removeSharingInArray(key:)), with:key, afterDelay:0.2);
            } else{
                element.confirmed=false
            }
        }

Yet the compiler reports the following error while processing the usage of variable 'element':

Value of tuple type '(key: Int, value: SharingElement)' has no member 'confirmed'

Like 'element' took the full tuple father than the part of its competence. Is the problem in the use of enumerated() or in the processing of the dictionary and how may I fix it?

Answer

Sulthan picture Sulthan · Jul 14, 2016

Use element.value.confirmed. element is a tuple that contains both key and value.

But you probably just want to remove enumerated():

for (key, element) in self.sharingDictionary {
    ...
}

enumerated() takes the iteration and adds indices starting with zero. That's not very common to use with dictionaries.