![](/img/trans.png)
[英]How to implement to a generic protocol, which has a function using the Type of associatedtype?
[英]Using associatedtype in a delegate protocol for a generic type
我有一个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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.