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)
}
}
我已經做了約束MyType
是Doable
,但編譯器抱怨說,它不能轉換(Array<Self.MyType>) -> Array<Self.MyType> to expected argument type (Array<Doable>) -> Array<Doable>
。任何人都可以解釋一下這裏發生了什麼,以及我如何讓編譯器高興?
優秀的解釋。感謝您的鏈接了。這就是我喜歡SO的原因。 – Erik