在委托协议中为通用类型使用associatedtype [英] Using associatedtype in a delegate protocol for a generic type

查看:122
本文介绍了在委托协议中为通用类型使用associatedtype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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 Boards.

这篇关于在委托协议中为通用类型使用associatedtype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆