standousset
standousset

Reputation: 1161

Completion handler in For/In loop - swift

How can you implement a completion handler in a For/In loop ? I have an array of two CNLabeledContact called phonesArray:

var myPhoneNumberArray = CNLabeledValue

for item in phonesArray {

   let phonesArrayValue = item.value as! CNPhoneNumber
   let phonesArrayValueDigits = phonesArrayValue.valueForKey("digits")! 
   print("current value: \(phonesArrayValueDigits)") //

   DataService.dataService.checkIfPhoneExistsInDatabase("\(phonesArrayValueDigits)") { (bool) in       
             if bool {
                print("append this item")
                self.myPhoneNumberArray.append(item)
             }
             else {
             }
     }
}
print("My phonenumbers array is:")
print(myPhoneNumberArray)

This, running, prints:

current value: 37439
current value: 78735
My phonenumbers array is:
[]
append this item //Only the second number matches the database and is appenned

I would like:

current value: 37439
Current value: 78735
append this item
[<CNLabeledValue:....digits=78735>>]

Upvotes: 2

Views: 1236

Answers (1)

Eiko
Eiko

Reputation: 25632

Looks as if checkIfPhoneExistsInDatabase is doing an asynchronous job. So the rest of your code can run at any time before, after, or in-between your completion handler.

So if your DataService instance doesn't provide synchronous operation or some synchronization, you have to manually do that job in your completion block. Your main point of interest will be to check if all items have been processed. Be careful about race conditions.

Another idea would be to serialize the queries, basically pulling the loop into the completion handler: just do the query on the first element, and within the block, query the data for the next element and so on.

Upvotes: 1

Related Questions