I create a function class : Bar, Bar use delegate that belong it to specific do something and this delegate comply with protocol FooDelegate, something like that:
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!
}
but in class Bar : var delegate:FooDelegate! I got an error:
Protocol 'FooDelegate' can only be used as a generic constraint because it has Self or associated type requirements
How could I fix this?
You have a couple of options.
Firstly you can use a specific type of FooDelegate, like SomeFoo:
class Bar {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: SomeFoo!
}
Or you can make Bar generic and define what type of Item the delegate needs:
class Bar<F> where F: FooDelegate, F.Item == Int {
//In Bar instance runtime ,it will call delegate to do something...
var delegate: F!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With