2017-12-02 24 views
0

나는 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? 
} 
+0

관련 유형을 제거하고 일반 함수'게임 '을 사용하는 것이 가능합니까? – Qbyte

+0

'GamePointsDelegate'는 타입이 아니기 때문에'GamePointsDelegate' 타입의'var pointsDelegate'를 가질 수 없습니다. 그것은 타입을위한 템플릿과 같아서, 가능한 모든 값'B'에 대해 새로운 타입을 생성합니다. – Alexander

+0

@Alexander, 이해합니다. 하지만 이미'게임'에'B'가 있는데 어떻게 든 사용하고 싶습니다. – kelin

답변

1

당신은 당신의 프로토콜과 관련된 유형의 요구 사항을 제거하고 대신에 일반적인 기능 game 사용할 수 있습니다 그대로

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

그래서 당신은 당신의 Game 클래스의 코드를 사용할 수 있지만 단점이다 프로토콜을 따르는 클래스는 모두 Board을 처리해야합니다.

+1

이렇게하면 다음과 같은 경고 메시지가 나타납니다. "중복 적합성 제약 조건 'B': 'Board'". 하지만 제네릭 선언에서 'Board'를 제거하면 모든 것이 컴파일됩니다. 감사! – kelin