繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM