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?
For iterating over arrays and dictionaries we have to use the for-in, forEach loop 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With