通过符合Swift 2中的协议来扩展类型化数组

通过符合Swift 2中的协议来扩展类型化数组

问题描述:

我想扩展一个类型数组 Array< SomeType> ,以便它符合协议 SomeProtocol 。现在我知道你可以像下面这样扩展一个类型数组:

I want to extend a typed array Array<SomeType> so that it conforms to a protocol SomeProtocol. Now I know you can extend a typed array like below:

extension Array where Element: SomeType { ... }

你也可以扩展一个对象来符合这样的协议:

And you can also extend an object to conform to a protocol like so:

extension Array: SomeProtocol { ...  }

但是我找不出什么样的正确语法来让类型数组符合协议,例如:

But I can't figure out what's the right syntax to have the typed array conform to a protocol, something like:

extension (Array where Element: SomeType): SomeProtocol { ... }

任何Swift 2专家知道如何做到这一点?

Any Swift 2 experts know how to do this?

您无法应用大量的逻辑来符合。它要么符合,要么不符合。但是,您可以将一点逻辑应用于扩展。下面的代码可以很容易地设置一致性的具体实现。这是重要的部分。

You can't apply a lot of logic to conformance. It either does or does not conform. You can however apply a little bit of logic to extensions. The code below makes it easy to set specific implementations of conformance. Which is the important part.

稍后将用作类型化约束。

This is used as a typed constraint later.

class SomeType { }

这是您的协议

This is your protocol

protocol SomeProtocol {

    func foo()

}

这是该协议的延伸。在 SomeProtocol 的扩展中实现 foo()会创建一个默认值。

This is an extension of the protocol. The implementation of foo() in an extension of SomeProtocol creates a default.

extension SomeProtocol {

    func foo() {
        print("general")
    }
}

现在 Array 符合 SomeProtocol 使用默认实现 foo()。所有的数组现在都有 foo()作为一种方法,这不是超级优雅。但它没有做任何事情,所以它不会伤害任何人。

Now Array conforms to SomeProtocol using the default implementation of foo(). All arrays will now have foo() as a method, which is not super elegant. But it doesn't do anything, so it's not hurting anyone.

extension Array : SomeProtocol {}

现在很酷的东西:
如果我们创建一个扩展到 Array $ c $对于元素,我们可以覆盖 foo()

Now the cool stuff: If we create an extension to Array with a type constraint for Element we can override the default implementation of foo()

extension Array where Element : SomeType {
    func foo() {
        print("specific")
    }
}

测试:

Tests:

let arrayOfInt = [1,2,3]
arrayOfInt.foo() // prints "general"

let arrayOfSome = [SomeType()]
arrayOfSome.foo() // prints "specific"