2017-04-02 83 views
1

我正在編寫一些代碼片段,以瞭解關聯類型如何工作,但我遇到了一個錯誤,我不知道如何解釋。我寫的代碼發佈在下面供參考。在Swift協議中約束關聯的類型

// A basic protocol 
protocol Doable { 
    func doSomething() -> Bool 
} 

// An extension that adds a method to arrays containing Doables 
extension Array where Element: Doable { 

    func modify(using function:(Array<Doable>)->Array<Doable>) -> Array<Doable> { 
     return function(self) 
    } 
} 

// Another protocol with an associated type constrained to be Doable 
protocol MyProtocol { 
    associatedtype MyType: Doable 

    func doers() -> Array<MyType> 

    func change(_:Array<MyType>) -> Array<MyType> 
} 

// An simple extension 
extension MyProtocol { 

    func modifyDoers() -> Array<MyType> { 
     return doers().modify(using: change) 
    } 
} 

我已經做了約束MyTypeDoable,但編譯器抱怨說,它不能轉換(Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>。任何人都可以解釋一下這裏發生了什麼,以及我如何讓編譯器高興?

回答

1

如錯誤消息所示,modify函數需要類型爲Array<Doable>的參數,並且您傳遞的參數類型爲Array<MyType>

問題從modify定義,在那裏你明確的參數使用Doable,排除所有其他類型,但Doable莖 - 和相關類型不是類型別名,MyType不能轉換爲Doable

修復的方法是改變Doable所有出現在modify功能Element,隨着斯威夫特文檔中被描繪:Extensions with a Generic Where Clause

+0

優秀的解釋。感謝您的鏈接了。這就是我喜歡SO的原因。 – Erik