나는 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?
}
관련 유형을 제거하고 일반 함수'게임 '을 사용하는 것이 가능합니까? – Qbyte
'GamePointsDelegate'는 타입이 아니기 때문에'GamePointsDelegate' 타입의'var pointsDelegate'를 가질 수 없습니다. 그것은 타입을위한 템플릿과 같아서, 가능한 모든 값'B'에 대해 새로운 타입을 생성합니다. – Alexander
@Alexander, 이해합니다. 하지만 이미'게임'에'B'가 있는데 어떻게 든 사용하고 싶습니다. – kelin