问题
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!
回答1:
(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.
来源:https://stackoverflow.com/questions/40412179/ios-swift-closures-callbacks-versus-delegates-when-to-use-which