7

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?

Fabrizio Bartolomucci
  • 4,948
  • 8
  • 43
  • 75

3 Answers3

26

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
0

This should do the trick,

        localDictionary.enumerateKeysAndObjects ({ (key, value, stop) -> Void in

    })
-4

I ended up implementing the thing as:

DispatchQueue.global(attributes: .qosBackground).async{
            for (key, element) in self.sharingDictionary{
                if !element.confirmed{
                    DispatchQueue.main.async({
                        element.deleteMe()
                        self.removeSharingInArray(key:key)
                    })
                } else{
                    element.confirmed=false
                }
            }
        }

So to hopefully delete the object without changing the Dictionary while it is browsed, what used to crash the app, even if I do not know if it still the case.

Fabrizio Bartolomucci
  • 4,948
  • 8
  • 43
  • 75