2016-11-02 69 views
1

我需要聲明兩個協議,它們都具有associatedtypes:如何在兩個協議之間共享關聯類型?

protocol MyView { 
    associatedtype DataType 
    associatedtype LayoutType : MyLayout 

    var data: DataType { get } 
    var layout: LayoutType { get } 

    func doLayout() 
} 

protocol MyLayout { 
    associatedtype DataType 

    func computeLayout(with data: DataType?) 
} 

按照目前的協議定義,MyViewassociatedtype DataType是不是真的一樣的一個在MyLayout

extension MyView { 
    func doLayout() { 
    layout.computeLayout(with: self.data) 
           ^^^^^^^^^ 
    Cannot convert value of type 'Self.DataType' to expected argument type '_?' 
    } 
} 

的編譯器告訴我們這個類型是不一樣的。

有沒有辦法在兩種協議之間共享關聯類型來解決我的問題?謝謝。

+0

也許你的意思是讓來自其他2 – Alexander

+0

@AlexanderMomchliov繼承的協議 - 我已經嘗試過(https://gist.github.com/anonymous/58fb6e95549081ba8eff9c7fc81d6fc2),它失敗,出現同樣的錯誤。 – MartinMoizard

回答

2

問題是,MyView的實現可能有一個LayoutType,其自身的DataTypeDataType不同。一旦SE-0142: Permit where clauses to constrain associated types實現,你只能夠說:

associatedtype LayoutType : MyLayout where LayoutType.DataType == DataType 

,以強制執行符合類型必須有一個相匹配DataType一個LayoutType

但是,在這種情況發生之前,您可能要做的最好的事情是將約束添加到擴展中 - 如果DataType匹配,則只會使默認實現doLayout()可用。

extension MyView where LayoutType.DataType == DataType { 
    func doLayout() { 
     layout.computeLayout(with: data) 
    } 
}