Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass protocol with associated type (generic protocol) as parameter in Swift?

Tags:

generics

swift

I have to pass an interface as a parameter to a function. Interface is generic a.k.a. has a associated type. I couldn't find a good way to do that. Here is my code:

protocol IObserver : class {
    typealias DelegateT
    ...
}

class Observer: IObserver {
    typealias DelegateT = IGeneralEventsDelegate // IGeneralEventsDelegate is a protocol
    ...
}

func notify(observer: IObserver) { ... } // here I need a type for observer param

I found that this will work:

func notify<T: IObserver where T.DelegateT == IGeneralEventsDelegate>(observer: T) { ... }

, but come on that is too complicated. What if I want to save this param in class variable, should I make the whole class generic, just because of this function.

It is true that I'm C++ developer and I'm new to the Swift language, but the way the things are done are far too complicated and user unfriendly ... or I'm too stupid :)

like image 915
devfreak Avatar asked Oct 12 '14 15:10

devfreak


1 Answers

If you use typealias in a protocol to make it generic-like, then you cannot use it as a variable type until the associated type is resolved. As you have probably experienced, using a protocol with associated type to define a variable (or function parameter) results in a compilation error:

Protocol 'MyProtocol' can only be used as a generic constraint because it has Self os associated type requirements

That means you cannot use it as a concrete type.

So the only 2 ways I am aware of to use a protocol with associated type as a concrete type are:

  • indirectly, by creating a class that implements it. Probably not what you have planned to do
  • making explicit the associated type like you did in your func

See also related answer https://stackoverflow.com/a/26271483/148357

like image 170
Antonio Avatar answered Oct 03 '22 09:10

Antonio