在委托协议中为通用类型使用associatedtype [英] Using associatedtype in a delegate protocol for a generic type
问题描述
我有一个Game
类.之所以将其设为通用,是因为我需要支持不同类型的电路板.现在,我只想添加一个经典的iOS风格的委托,其方法将以游戏和新的points值作为参数.如何以Swift associatedtype
的方式实现这一目标?我真的很困惑,我无法实现这种简单的逻辑.
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?
}
推荐答案
您可以从协议中删除关联的类型要求,而改用通用函数game
:
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)
}
因此,您可以按原样使用Game
类的代码,但缺点是符合协议的类必须处理所有Board
.
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.
这篇关于在委托协议中为通用类型使用associatedtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!