hop*_*opy 3 generics swift swift-protocols
我创建了一个函数类: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!
}
Run Code Online (Sandbox Code Playgroud)
但是在课堂上Bar:var delegate:FooDelegate!我收到了一个错误:
协议'FooDelegate'只能用作通用约束,因为它具有Self或相关类型要求
我怎么能解决这个问题?
你有几个选择.
首先,您可以使用特定类型FooDelegate,例如SomeFoo:
class Bar {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: SomeFoo!
}
Run Code Online (Sandbox Code Playgroud)
或者您可以创建Bar泛型并定义Item委托所需的类型:
class Bar<F> where F: FooDelegate, F.Item == Int {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: F!
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
324 次 |
| 最近记录: |