How to make async / await in Swift?

后端 未结 5 2023
别跟我提以往
别跟我提以往 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 15:47

    (Note: Swift 5 may support await as you’d expect it in ES6!)

    What you want to look into is Swift's concept of "closures". These were previously known as "blocks" in Objective-C, or completion handlers.

    Where the similarity in JavaScript and Swift come into play, is that both allow you to pass a "callback" function to another function, and have it execute when the long-running operation is complete. For example, this in Swift:

    func longRunningOp(searchString: String, completion: (result: String) -> Void) {
        // call the completion handler/callback function
        completion(searchOp.result)
    }
    longRunningOp(searchString) {(result: String) in
        // do something with result
    }        
    

    would look like this in JavaScript:

    var longRunningOp = function (searchString, callback) {
        // call the callback
        callback(err, result)
    }
    longRunningOp(searchString, function(err, result) {
        // Do something with the result
    })
    

    There's also a few libraries out there, notably a new one by Google that translates closures into promises: https://github.com/google/promises. These might give you a little closer parity with await and async.

提交回复
热议问题