【发布时间】:2018-03-30 06:41:48
【问题描述】:
我创建了一个函数类:Bar,Bar 使用属于它的委托做某事并且这个委托符合协议FooDelegate,类似这样:
protocol FooDelegate{
associatedtype Item
func invoke(_ item:Item)
}
class SomeFoo:FooDelegate{
typealias Item = Int
func invoke(_ item: Int) {
//do something...
}
}
class Bar{
//In Bar instance runtime ,it will call delegate to do something...
var delegate:FooDelegate!
}
但是在 Bar 类中:var delegate:FooDelegate! 我得到了一个错误:
Protocol 'FooDelegate' 只能用作通用约束 因为它有 Self 或关联的类型要求
我该如何解决这个问题?
【问题讨论】:
-
您收到此错误是因为
FooDelegate具有关联类型item。不确定您的情况,但您可能想要类型擦除。 -
你是对的!我知道。但是你能谈谈类型擦除的细节吗,谢谢
标签: swift generics swift-protocols