TruMan1 TruMan1 - 3 months ago 21
Swift Question

How to extend type that accepts generic elements of array?

I have a type that I'm trying to specifically extend:

. It would be easy to extend if I wasn't passing in an an array as the
, which I can do something like this:

extension AnyObserver where Element: MyModel {...}

However, actually
is an array, so I tried to do something like either of the below:

extension AnyObserver where Element: Array<MyModel> {...}
extension AnyObserver where Element: Array<T: MyModel> {...}
extension AnyObserver where Element == Array<MyModel> {...}
extension AnyObserver where Element == [MyModel] {...}

These result in compile errors such as:

Same-type requirement makes generic parameter non-generic
Type 'Element' constrained to non-protocol type

What is the correct way create an extension for this case?


In general you cannot extend a generic type based on a specific type parameter. You can only extend based on a protocol. But in your particular case, that gives us an out. Just don't require an Array. Require a CollectionType.

extension AnyObserver
    where Element: CollectionType, Element.Generator.Element == MyModel {