Using associatedtype in a delegate protocol for a generic type

断了今生、忘了曾经 提交于 2019-12-24 07:50:40

问题


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?
}

回答1:


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.



来源:https://stackoverflow.com/questions/47612406/using-associatedtype-in-a-delegate-protocol-for-a-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!