Swift:符合使用扩展和组合模式的协议
Swift: conforming to protocol using extension and composition pattern
在此 PDF 的幻灯片 62 上:Some Columbia College Presentation 它说 Swift 及其扩展背后的想法之一是使用组合模式来符合协议。
现在我理解了 Swift
中扩展的语法
//example from Apple:
extension SomeType: SomeProtocol, AnotherProtocol {
// implementations of not yet provided functions and properties of SomeType go here
}
但是构图模式有什么关系呢?这家伙的意思是 复合 模式描述 here,对吧?有人可以提供一个如何使用它的最小示例吗?
Composition
指"implementing"接口,在Swift中称为符合protocols
。
围栏的另一边是 Inheritance
,您可以在那里扩展 classes。
这里的主要问题是您只能扩展一个 class 但可以根据需要符合任意多的接口(至少在 Swift 中)。因此,如果您的 class 想成为 UITableViewDelegate
和 UITableViewDataSource
,您只能通过组合来实现。
Interfaces/Protocols 给开发人员更多的开放空间,而不是 class 你能做的。协议仅 定义 函数和方法 - 并且在 Swift 属性中,它们本身具有一些类似函数的功能。 类 另一方面可以包含变量、常量等。它们已经可以实现其中的一些——这是接口通常做不到的。
在此 PDF 的幻灯片 62 上:Some Columbia College Presentation 它说 Swift 及其扩展背后的想法之一是使用组合模式来符合协议。
现在我理解了 Swift
中扩展的语法//example from Apple:
extension SomeType: SomeProtocol, AnotherProtocol {
// implementations of not yet provided functions and properties of SomeType go here
}
但是构图模式有什么关系呢?这家伙的意思是 复合 模式描述 here,对吧?有人可以提供一个如何使用它的最小示例吗?
Composition
指"implementing"接口,在Swift中称为符合protocols
。
围栏的另一边是 Inheritance
,您可以在那里扩展 classes。
这里的主要问题是您只能扩展一个 class 但可以根据需要符合任意多的接口(至少在 Swift 中)。因此,如果您的 class 想成为 UITableViewDelegate
和 UITableViewDataSource
,您只能通过组合来实现。
Interfaces/Protocols 给开发人员更多的开放空间,而不是 class 你能做的。协议仅 定义 函数和方法 - 并且在 Swift 属性中,它们本身具有一些类似函数的功能。 类 另一方面可以包含变量、常量等。它们已经可以实现其中的一些——这是接口通常做不到的。