How do I dispatch functions in Swift the right way?

后端 未结 1 1837
别那么骄傲
别那么骄傲 2020-12-09 05:13

I\'ve kept trying but I just don\'t get it. I\'m rather new to programming so almost every new step is an experiment. Whereas I have no problems dispatching normal closures

相关标签:
1条回答
  • 2020-12-09 06:01

    Let's say you had some function like so:

    func calculate(foo: String, bar: Int) -> Int {
        // slow calculations performed here
    
        return result
    }
    

    If you wanted to do that asynchronously, you could wrap it in something like this:

    func calculate(foo: String, bar: Int, completionHandler: @escaping (Int) -> Void) {
        DispatchQueue.global().async {
            // slow calculations performed here
    
            completionHandler(result)
        }
    }
    

    Or, alternatively, if you want to ensure the completion handler is always called on the main queue, you could have this do that for you, too:

    func calculate(foo: String, bar: Int, completionHandler: @escaping (Int) -> Void) {
        DispatchQueue.global().async {
            // slow calculations performed here
    
            DispatchQueue.main.async {           
                completionHandler(result)
            }
        }
    }
    

    For the work being performed in the background, you may use a different priority background queue, or your might use your own custom queue or your own operation queue. But those details aren't really material to the question at hand.

    What is relevant is that this function, itself, doesn't return any value even though the underlying synchronous function does. Instead, this asynchronous rendition is passing the value back via the completionHandler closure. Thus, you would use it like so:

    calculate(foo: "life", bar: 42) { result in
        // we can use the `result` here (e.g. update model or UI accordingly)
    
        print("the result is = \(result)")
    }
    
    // but don't try to use `result` here, because we get here immediately, before
    // the above slow, asynchronous process is done
    

    (FYI, all of the above examples are Swift 3. For Swift 2.3 rendition, see previous version of this answer.)

    0 讨论(0)
提交回复
热议问题