簡體   English   中英

在Swift 2中實現擴展協議

[英]Implementing a protocol with extension in Swift 2

我有這樣的protocol

protocol Parent { 
    associatedtype ValueType

    mutating func foo(value: ValueType) -> Void
}

我將其擴展到另一個protocol

protocol Child: Parent {
    var storedProperty: SomeRandomType? // Need this for the extension!
}

然后在這里實現一些默認行為,如下所示:

extension Child {
    mutating func foo(value: ValueType) -> Void {
        // Ensure storedProperty is initialised and 
        // store value into storedProperty
    }
}

現在,在一個測試案例中

struct MyChildImpl: Child {
    typealias ValueType = AnotherRandomType
}

此時,XCode向我顯示了3個錯誤:

  • 類型'MyChildImpl'不符合協議'Child'
  • 類型“ MyChildImpl”不符合協議“父母”
  • 協議'Child'只能用作一般約束,因為它具有Self或關聯的類型要求

這是我第一次為具有“ mixins”的結構切換單基類-我在做什么錯?

謝謝你的時間!

因為您在協議的定義中分配了協議,所以您不能在擴展中推遲協議的遵從性。 必須在分配協議的塊內執行所有協議合規性。

這與編譯器(處於當前狀態)如何檢查協議符合性有關。 這說明了您的錯誤。

我的主要問題是Protocol 'Child' can only be used as a generic constraint because it has Self or associated type requirements (其他Protocol 'Child' can only be used as a generic constraint because it has Self or associated type requirements相當微不足道)-我決定使用Type Erasure來解決它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM