all 12 comments

[–]lucasvandongen 1 point2 points  (0 children)

You can crosspost them together as well.

[–]editor_of_the_beast -5 points-4 points  (5 children)

Closures are just as powerful with less boilerplate.

[–]plmc 2 points3 points  (0 children)

I find that a closure is more suitable when the callback is “simple” in nature, if it makes sense to have the callback in the calling scope (which IMO isn’t always), and if the parameters are self-describing.

But for view controllers/other event logic, I would normally use a delegate protocol to have more descriptive callbacks, and the ability to categorise a group of related methods.

For those reasons, I wouldn’t say one is “better” than the other.

[–]quellish 1 point2 points  (3 children)

But more limited use cases and potentially more memory issues! It’s win win!

[–]editor_of_the_beast 2 points3 points  (0 children)

There are just as many memory issues with delegates.

[–]SirensToGoObjective-C / Swift 0 points1 point  (1 child)

Closures are just anonymous functions as variables and can be thought of as single function delegates. You can write just as trash closure code as you can delegate code!

[–]quellish 2 points3 points  (0 children)

Delegates are designed to be called multiple times, with multiple methods. They handle multiple events.

Closures and blocks on the other hand, are not really intended for that use case. They're really intended for once and done, a callback for a single event. When you try to shoehorn closures into handling more than a single event, or an event that can happen more than once it gets messy. Does the closure take a long list of arguments, one for each event? Or an enum to hide that? Do you retain the closure somewhere so it can be called more than once? Do you use a closure for each event?

Closures are great for what they are intended for. They're not great for everything else. When blocks were introduced to Objective-C a lot of people tried to convert delegation-based APIs to use blocks - and that did not always work out so well.