我有一个Game
类。我认为它是通用的,因为我需要支持不同类型的董事会。现在,我只想添加一个可以使用游戏和新点值作为参数的方法的经典iOS式委托。如何以Swift associatedtype
方式实现这一目标?我真的很困惑,因为我不能这样简单逻辑。
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?
}
您可以从协议中删除关联的类型要求,然后使用通用函数game
而不是:
protocol GamePointsDelegate {
func game<B>(_ game: Game<B>, didSetPoints points: Int)
}
因此,您可以使用Game
类的代码,但缺点是,符合协议的类必须处理所有Board
s。