swift – 如果在扩展中实现协议方法,是否需要在协议中指定方法?

swift – 如果在扩展中实现协议方法,是否需要在协议中指定方法?,第1张

概述参见英文答案 > Reasons to include function in protocol definition vs. only defining it in the extension?                                    1个 >             Swift protocol extension method is called instead 参见英文答案 > Reasons to include function in protocol definition vs. only defining it in the extension?                                    1个
>             Swift protocol extension method is called instead of method implemented in subclass                                    3个
我喜欢Swift如何让你在协议中定义一个方法,然后通过该协议的扩展,实现该方法.但是,特别是对于在同一范围内定义协议和扩展且具有相同访问级别的情况,您是否需要首先在协议中定义方法?

考虑以下代码:

public protocol MyProtocol {    func addThese(a:Int,b:Int) -> Int}public extension MyProtocol {    func addThese(a:Int,b:Int) -> Int{        return a + b    }}

这有什么不同呢?

public protocol MyProtocol {}public extension MyProtocol {    func addThese(a:Int,b:Int) -> Int{        return a + b    }}

注意:我特别询问协议和扩展是否在同一范围内以相同的访问级别一起定义.

如果不是这样 – 即.扩展名与协议的范围不同 – 显然只有与扩展名相同范围内的项才能获得自动实现.那讲得通.

即在模块A中:

public protocol MyProtocol {    func addThese(a:Int,b:Int) -> Int}

在模块B中

internal extension MyProtocol {    func addThese(a:Int,b:Int) -> Int{        return a + b    }}

模块B中实现MyProtocol的所有项目将自动获得addThese的实现,而在不同范围内实现MyProtocol的项目仍然必须明确满足协议.

同样,这特别是围绕定义协议和扩展.是否需要在协议本身中定义函数,还是仅仅考虑好的做法?

解决方法 您不需要在协议中定义方法,您可以像使用扩展名一样使用扩展来添加方法,我已经多次完成了.我认为这是一种方便的方法,可以为已经符合协议的类提供一些继承.

实际上,您甚至可以扩展本机协议,例如UItableVIEwDataSource或UItableVIEwDelegate.例如,您可能希望处理表视图的所有视图控制器都可以访问一个方便的方法.

但是,对于您自己的协议,我建议将这些扩展保存在与协议声明相同的文件中,以便更好地跟踪与协议相关的所有内容.

如果仍有疑问,您可以阅读文档:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

Extensions add new functionality to an existing class,structure,
enumeration,or protocol type

所以我不相信这是不好的做法,你只是添加新的功能.

总结

以上是内存溢出为你收集整理的swift – 如果在扩展中实现协议方法,是否需要在协议中指定方法?全部内容,希望文章能够帮你解决swift – 如果在扩展中实现协议方法,是否需要在协议中指定方法?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1003222.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存