Is there any particular use of closure in swift? and what's the benefit?

后端 未结 2 1340
余生分开走
余生分开走 2021-01-28 07:42

I have learnt Swift for a while and I have read the Swift language guide.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_

2条回答
  •  不知归路
    2021-01-28 08:14

    Closures are a concept you use mainly on asynchronous function calls. (at least I do so)

    A good example where Apple uses closures is URLSession:

    func downloadTask(with url: URL, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> URLSessionDownloadTask
    

    This method creates an URLSessionDownloadTask that runs in a background thread. When you call this method, you are passing a closure as completionHandler. This closure is executed, when the task has finished.


    There are some other cases, but I haven't used them this much yet, because I love the delegate pattern. I found an article that compares Closures and Delegates in Swift.

    Delegates in Swift have a big problem: Unless you are using @objc, you have to implement every method of a protocol, which could lead to lots of unnecessary code and would look confusing. That's why I guess it would be much better to use closures in many cases.

提交回复
热议问题