Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating along a Dictionary in Swift 3

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?

like image 315
Fabrizio Bartolomucci Avatar asked Jul 14 '16 18:07

Fabrizio Bartolomucci


People also ask

How do I iterate through a dictionary in Swift?

For iterating over arrays and dictionaries we have to use the for-in, forEach loop in Swift.

How to iterate array of dictionary in swift?

We can also use enumerated() to get the keys, value relative to their dictionary positions. It prints the values along with their index in the dictionary on the console. We can also use the higher-order function like forEach() to iterate over any collection.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.


1 Answers

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.

like image 150
Sulthan Avatar answered Oct 16 '22 14:10

Sulthan