我想扩展一个类型化数组Array SomeType这样它符合协议SomeProtocol.现在我知道你可以扩展一个类型化的数组,如下所示: extension Array where Element: SomeType { ... } 您还可以扩展对象以符合如下协
extension Array where Element: SomeType { ... }
您还可以扩展对象以符合如下协议:
extension Array: SomeProtocol { ... }
但我无法弄清楚使用类型数组符合协议的正确语法是什么,例如:
extension (Array where Element: SomeType): SomeProtocol { ... }
任何Swift 2专家都知道如何做到这一点?
您不能将大量逻辑应用于一致性.它要么符合要么不符合要求.但是,您可以对扩展应用一些逻辑.下面的代码可以轻松设置一致性的特定实现.哪个是重要的部分.稍后将其用作类型约束.
class SomeType { }
这是你的协议
protocol SomeProtocol { func foo() }
这是协议的扩展.在SomeProtocol的扩展中实现foo()会创建一个默认值.
extension SomeProtocol { func foo() { print("general") } }
现在,Array使用foo()的默认实现符合SomeProtocol.所有数组现在都将foo()作为一种方法,这不是超级优雅的.但它没有做任何事情,所以它不会伤害任何人.
extension Array : SomeProtocol {}
现在很酷的东西:
如果我们使用Element的类型约束创建Array的扩展,我们可以覆盖foo()的默认实现
extension Array where Element : SomeType { func foo() { print("specific") } }
测试:
let arrayOfInt = [1,2,3] arrayOfInt.foo() // prints "general" let arrayOfSome = [SomeType()] arrayOfSome.foo() // prints "specific"