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

标签 swift protocols swift-protocols swift-extensions

我喜欢 Swift 让您在协议(protocol)中定义方法,然后通过该协议(protocol)的扩展来实现该方法的方式。但是,特别是对于您在相同范围和相同访问级别定义协议(protocol)和扩展的情况,您是否需要首先在协议(protocol)中定义方法?

考虑这段代码:

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
    }
}

注意:我特别询问在相同范围内以相同访问级别一起定义的协议(protocol)和扩展。

如果情况并非如此——即扩展与协议(protocol)在不同的范围内——那么显然只有与扩展在相同范围内的项目才能自动实现。这是有道理的。

即在模块 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 的项目仍然会必须明确满足协议(protocol)。

同样,这特别是围绕一起定义协议(protocol)和扩展。是否需要在协议(protocol)本身中定义功能,或者它只是被认为是好的做法?

最佳答案

你不需要在协议(protocol)中定义方法,你可以像你说的那样使用扩展为协议(protocol)添加方法,我已经做过很多次了。我认为这是一种方便的方式,可以为已经符合协议(protocol)的类提供一些继承。

事实上,您甚至可以扩展 native 协议(protocol),例如 UITableViewDataSourceUITableViewDelegate。例如,您可能希望处理 TableView 的所有 View Controller 都可以访问一个方便的方法。

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

如果仍有疑问,您可以阅读文档: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 - 如果在扩展中实现协议(protocol)方法,是否需要在协议(protocol)中指定方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48193546/

相关文章:

ios - 一个 tableView 有两个不同的 cell.xib,如果我按下一个单元格,它需要显示第二个单元格。如何?

c++ - 如何理解 uart 端口收到了整个消息?

swift - 为什么我需要强制向下转换才能使用具有约束的协议(protocol)数组

swift - 如何将 self.dynamicType 变成类型别名

swift - 具有类型别名的协议(protocol)不能符合 AnyObject 类型?

ios - 如何为 UIView 创建拖动动画?

ios - 检查依赖性...没有要编译的体系结构(ARCHS=i386,VALID_ARCHS=arm64 armv7s armv7)

swift - 你真的可以在 AnyObject 上调用任何 Objective-C 方法吗?

python - 简单的服务器/客户端字符串交换协议(protocol)