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

限于喜欢 提交于 2020-02-26 09:14:42

问题


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 :)


回答1:


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



来源:https://stackoverflow.com/questions/26326477/how-to-pass-protocol-with-associated-type-generic-protocol-as-parameter-in-swi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!