iOS Swift: Closures (Callbacks) versus Delegates, when to use which?

16,324

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

Share:
16,324

Related videos on Youtube

RainCast
Author by

RainCast

Hey! check out my app from app store:

Updated on June 06, 2022

Comments

  • RainCast
    RainCast about 2 years

    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!

    • rmaddy
      rmaddy over 7 years
      Since your question has no good objective answer and will be closed soon, simply use the one that best solves a given problem.
    • RainCast
      RainCast over 7 years
      @rmaddy Thanks for your feedback. I'll update the question to be more specific. It's actually the same nature as questions like this: stackoverflow.com/questions/27703913/…
    • Rostyslav Druzhchenko
      Rostyslav Druzhchenko about 3 years
      Using delegates gives an important thing - they make connections between classes noticeable. When we use delegates, we see connections on the class description level. When we use actions, we see connections on the methods/properties level. Seeing connections on the class level is more beneficial for software design analysis. From this point of view, it's all about coupling clarity.
  • RainCast
    RainCast over 7 years
    I think this is a good point. thanks!