如何在Swift中将具有关联类型(通用协议)的协议作为参数传递? [英] How to pass protocol with associated type (generic protocol) as parameter in Swift?

查看:248
本文介绍了如何在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

我发现这可以工作:

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.

我确实是C ++开发人员,并且是Swift语言的新手,但是事情的完成方式太复杂了,用户也不友好...或者我太愚蠢了:)

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

推荐答案

如果在协议中使用typealias使其具有通用性,则在解析关联的类型之前,不能将其用作变量类型.您可能已经经历过,使用具有关联类型的协议来定义变量(或函数参数)会导致编译错误:

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:

协议'MyProtocol'只能用作通用约束,因为它具有与Self os关联的类型要求

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

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

这篇关于如何在Swift中将具有关联类型(通用协议)的协议作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆