我必须将接口(interface)作为参数传递给函数。接口(interface)是通用的,也就是具有关联类型。我找不到一个好的方法来做到这一点。这是我的代码:
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) { ... }
,但是拜托,这太复杂了。如果我想将这个参数保存在类变量中,我是否应该仅仅因为这个函数而使整个类通用。
的确,我是 C++ 开发人员并且我是 Swift 语言的新手,但是完成事情的方式太复杂而且用户不友好......或者我太愚蠢了:)
最佳答案
如果您在协议(protocol)中使用 typealias
使其具有类通用性,那么在解析相关类型之前,您不能将其用作变量类型。正如您可能遇到的那样,使用具有关联类型的协议(protocol)来定义变量(或函数参数)会导致编译错误:
Protocol 'MyProtocol' can only be used as a generic constraint because it has Self os associated type requirements
这意味着您不能将其用作具体类型。
因此,我所知道的将具有关联类型的协议(protocol)用作具体类型的仅有两种方式是:
- 间接地,通过创建一个实现它的类。可能不是你计划做的事
- 像在函数中那样明确关联类型
关于swift - 如何在 Swift 中将关联类型(通用协议(protocol))的协议(protocol)作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26326477/