在委托协议中使用关联类型作为泛型类型

时间:2017-12-02 20:44:07

标签: swift generics protocols associated-types

我有一个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?
}

1 个答案:

答案 0 :(得分:3)

您可以从协议中删除关联的类型要求,并使用通用函数game代替:

protocol GamePointsDelegate {
    func game<B>(_ game: Game<B>, didSetPoints points: Int)
}

因此,您可以使用Game类的代码,但缺点是符合协议的类必须处理所有Board