iOS Swift:闭包(回调)与委托,何时使用哪个? [英] iOS Swift: Closures (Callbacks) versus Delegates, when to use which?

查看:33
本文介绍了iOS Swift:闭包(回调)与委托,何时使用哪个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就简单的逻辑关联而言,我个人更喜欢 Swift 中的回调而不是委托,因为它非常直接且易于理解.同时,有些人更喜欢委托,因为委托是其他语言中的流行模式,例如 C#.

我在网上找到了一些讨论:

1.为什么不应该在 Swift 中使用委托?"https://medium.cobeisfresh.com/why-you-shouldn-t-use-delegates-in-swift-7ef808a7f16b#.hqb7zrc1v

2.苹果正在将注意力更多地转移到回调模式上https://www.reddit.com/r/swift/comments/2ces1q/closures_vs_delegates/

3.块或代表?http://blog.stablekernel.com/blocks-or-delegates/>

阅读这些讨论后,我仍然没有决定偏好.我想知道什么时候使用闭包更好,什么时候使用委托更好?和原因?

谢谢!

解决方案

(针对基于意见的问题的基于意见的答案)

问题不应该是哪个更好,而应该是我试图解决的问题的最佳解决方案.

我的简单规则:如果某些东西需要一个函数作为它的接口,回调通常是一个很好的解决方案.如果需要多个函数,尤其是对象的基本功能需要它们时,Delegate 可能是更好的解决方案.

一如既往,这取决于具体情况,但绝对语句在实际使用中很少奏效.

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!

解决方案

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

这篇关于iOS Swift:闭包(回调)与委托,何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆