在泛型类型的委托协议中使用关联类型
Using associatedtype in a delegate protocol for a generic type
我有一个Game
class。我把它做成通用的,因为我需要支持不同类型的板。现在我只想添加一个 classical 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
class 的代码,但缺点是符合协议的 class 必须处理所有 Board
s.
我有一个Game
class。我把它做成通用的,因为我需要支持不同类型的板。现在我只想添加一个 classical 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
class 的代码,但缺点是符合协议的 class 必须处理所有 Board
s.