Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using associatedtype in a delegate protocol for a generic type

I have a Game class. I made it generic because I was need to support different types of boards. Now I just want to add a classical iOS-style delegate with a method which will take a game and a new points value as parameters. How to achieve this in the Swift associatedtype way? I really confused that I can't impelemnt such simple logic.

protocol GamePointsDelegate {
    associatedtype B: Board
    func game(_ game: Game<B>, didSetPoints points: Int)
}

class Game<B: Board> {
    let board: Board

    var points = 0 {
        // Compiler Error
        // Member 'game' cannot be used on value of protocol type 'GamePointsDelegate'; use a generic constraint instead
        didSet { pointsDelegate?.game(self, didSetPoints: points) }
    }

    // Compiler Error
    // Protocol 'GamePointsDelegate' can only be used as a generic constraint because it has Self or associated type requirements
    var pointsDelegate: GamePointsDelegate?
}
like image 418
kelin Avatar asked Oct 16 '25 15:10

kelin


1 Answers

You could remove the associated type requirement from your protocol and use a generic function game instead:

protocol GamePointsDelegate {
    func game<B>(_ game: Game<B>, didSetPoints points: Int)
}

So you can use the code of your Game class as it is but the downside is that the class which conforms to the protocol has to handle all Boards.

like image 101
Qbyte Avatar answered Oct 18 '25 11:10

Qbyte



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!