问题
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