加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:32:18 所属栏目:百科 来源:网络整理
导读:参见英文答案 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?
参见英文答案 > 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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读