[英]Using associatedtype in a delegate protocol for a generic type
I have a Game
class. 我有一个
Game
课。 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.
现在我只想添加一个经典的iOS风格的委托,其方法是将游戏和新的点值作为参数。 How to achieve this in the Swift
associatedtype
way? 如何以Swift
associatedtype
方式实现这一点? 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?
}
You could remove the associated type requirement from your protocol and use a generic function game
instead: 您可以从协议中删除关联的类型要求,并使用通用函数
game
:
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 Board
s. 因此,您可以使用
Game
类的代码,但缺点是符合协议的类必须处理所有Board
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.