How to make async / await in Swift?

后端 未结 5 2015
别跟我提以往
别跟我提以往 2020-12-28 14:53

I would like to simulate async and await request from Javascript to Swift 4. I searched a lot on how to do it, and I thought I found the answer with DispatchQueue

5条回答
  •  伪装坚强ぢ
    2020-12-28 16:00

    Thanks to vadian's comment, I found what I expected, and it's pretty easy. I use DispatchGroup(), group.enter(), group.leave() and group.notify(queue: .main){}.

    func myFunction() {
        let array = [Object]()
        let group = DispatchGroup() // initialize
    
        array.forEach { obj in
    
            // Here is an example of an asynchronous request which use a callback
            group.enter() // wait
            LogoRequest.init().downloadImage(url: obj.url) { (data) in
                if (data) {
                    group.leave() // continue the loop
                }
            }
        }
    
        group.notify(queue: .main) {
            // do something here when loop finished
        }
    }
    

提交回复
热议问题