Search code examples
swiftgenericsswift2swift-extensions

Extension for CollectionType with element of certain type ignores subtypes


I'm trying to create an extension for collection types containing elements of a certain type FooType and this works just fine:

extension CollectionType where Generator.Element == FooClass
{
    func doSomething()
}

let collectionType = [FooClass]()
collectionType.doSomething()

My problem is that I also want this extension to work for collection types that contain subclasses of the Foo class:

let collectionType = [FooSubclass]()
collectionType.doSomething()    // Doesn't work

I could possibly override the "==" operator and and loop through the chain of super classes until I've got a match but not sure if this is the right way to do it.

public func ==(t0: Any.Type?, t1: Any.Type?) -> Bool

Am I missing something in my where clause that could solve this or am I doing this totally wrong?


Solution

  • Use : instead of ==.

    Try:

    extension CollectionType where Generator.Element: FooClass {