Completion handler in For/In loop - swift

守給你的承諾、 提交于 2019-12-22 12:43:30

问题


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>>]

回答1:


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.



来源:https://stackoverflow.com/questions/35850500/completion-handler-in-for-in-loop-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!