我必须将接口作为参数传递给函数.接口是通用的,也有相关的类型.我找不到一个很好的方法来做到这一点.这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
我发现这会起作用:
func notify<T: IObserver where T.DelegateT == IGeneralEventsDelegate>(observer: T) { ... }
Run Code Online (Sandbox Code Playgroud)
,但是来得太复杂了.如果我想在类变量中保存这个参数,我应该将整个类设为通用,只是因为这个函数.
确实,我是C++开发人员,而且我是Swift语言的新手,但事情的完成方式太复杂,用户不友好......或者我太傻了:)
如果您typealias
在协议中使用它使其类似通用,那么在解析关联类型之前,您不能将其用作变量类型.您可能已经遇到过,使用具有关联类型的协议来定义变量(或函数参数)会导致编译错误:
协议'MyProtocol'只能用作通用约束,因为它具有Self os关联类型要求
这意味着你不能将它用作具体类型.
因此,我知道使用具有关联类型的协议作为具体类型的唯一两种方法是:
另请参阅相关答案/sf/answers/1839003841/
归档时间: |
|
查看次数: |
4233 次 |
最近记录: |