Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Completion Handlers vs. Delegation when making API Calls [duplicate]

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!

like image 724
RainCast Avatar asked Nov 23 '25 01:11

RainCast


1 Answers

(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.

like image 110
GetSwifty Avatar answered Nov 24 '25 17:11

GetSwifty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!