简体   繁体   English

如何在Swift中传递具有关联类型(通用协议)的协议作为参数?

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

I have to pass an interface as a parameter to a function. 我必须将接口作为参数传递给函数。 Interface is generic aka 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 :) 确实,我是C ++开发人员,而且我是Swift语言的新手,但事情的完成方式太复杂,用户不友好......或者我太傻了:)

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. 如果在协议中使用typealias使其类似于泛型,则在解析关联类型之前,不能将其用作变量类型。 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 协议'MyProtocol'只能用作通用约束,因为它具有Self os关联类型要求

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 像你在func中那样显式地显示关联类型

See also related answer https://stackoverflow.com/a/26271483/148357 另请参阅相关答案https://stackoverflow.com/a/26271483/148357

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM