Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift protocol with associatedtype error

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?

like image 240
hopy Avatar asked Apr 19 '26 13:04

hopy


1 Answers

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!
}
like image 199
Guy Kogus Avatar answered Apr 22 '26 04:04

Guy Kogus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!