私はGame
クラスを持っています。私はそれを一般的にしました。なぜなら、さまざまなタイプのボードをサポートする必要があったからです。ここでは、古典的なiOSスタイルのデリゲートをゲームに追加するメソッドと新しいポイントの値をパラメータとして追加したいだけです。どのようにスウィフトassociatedtype
方法でこれを達成するには?私は本当にそのような単純な論理を打ち消すことはできないと私は混乱しました。汎用タイプの代理プロトコルで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'を使用することは可能でしょうか? – Qbyte
'GamePointsDelegate'は型ではないので、' GamePointsDelegate'型の 'var pointsDelegate'を持つことはできません。これは型のテンプレートのようなもので、 'B'のすべての値に対して新しい型を生成します。 – Alexander
@アレクサンダー、分かります。しかし、私はすでに 'ゲーム'に 'B'を持っていて、何とか使ってみたい。 – kelin