Personally I prefer callback over delegate in Swift for simple logical correlations, because it's pretty straight-forward and easy to understand. At the same time, some prefers delegate, since delegation is a popular pattern in other languages, such as C#.
There are some discussions I found online:
1. "Why you shouldn't use delegates in Swift?" https://medium.cobeisfresh.com/why-you-shouldn-t-use-delegates-in-swift-7ef808a7f16b#.hqb7zrc1v
2. Apple is shifting its focus more on the callback pattern https://www.reddit.com/r/swift/comments/2ces1q/closures_vs_delegates/
3. blocks or delegates? http://blog.stablekernel.com/blocks-or-delegates/
After reading these discussions, I am still undecided on the preference. I would like to know when is better to use closures and when is better to use delegates? and reasons?
Thanks!
Callbacks are similar in function to the delegate pattern. They do the same thing: letting other objects know when something happened, and passing data around. What differentiates them from the delegate pattern, is that instead of passing a reference to yourself, you are passing a function.
If you look at some delegate methods (and nearly all dataSource methods), there is an expected return value. That means the delegating object is asking for the state of something. While a closure could reasonably maintain state or at least deduce state, this is really an object's role. Think about it.
Closures in Swifttypealias completion = (Int) -> Void? A closure is simply a function with no name; you can pass it to a variable or pass it around like any other value. The idea is to make the same thing that we made with delegation using closure callbacks.
Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
(Opinion based answer for an opinion based question)
The questions shouldn't be which is better, it should be what's the best solution for the problem I'm trying to solve.
My simple rule: if something requires one function as it's interface, a callback is usually a good solution. If more than one function is required, especially when they're required for the basic function of an object, a Delegate is probably a better solution.
As always it depends on the specific situation, but absolute statements rarely work out in real-world usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With