2016-03-31 112 views
1

我的代碼如下所示:協議相關的類型和泛型

protocol Remotable { 
    init?(dict: Dictionary<String, String>) 
} 

protocol SearchResultable { 
    associatedtype TRS: Remotable 
    static func myFunction(remote: TRS) 
} 

struct MySearchResult<T:SearchResultable, TR: Remotable> { 
    typealias TRS = TR 
    let items: Array<T> 
    let limit: Int 

    func testMethod() { 
     let dict = [["id": "asd123"],["id":"asd456"]] 
     let a = dict.flatMap(TRS.init) 
     let b = a[0] //has type TR 
     let c = T.myFunction(... //expects an argument of type T.TRS 
    } 
} 

而且我不能打電話給myFunction的,因爲它預計參數的T.TRS類型。我期待着我可以用TR類型的b參數調用myFunction。你有什麼想法我做錯了什麼?

回答

1

我也找到了自己的問題的答案。我不知道哪一個更好,我會很感激,如果有人會解釋哪個更好,爲什麼。

struct MySearchResult<T:SearchResultable, TR where T.TRS == TR > { 
    let items: Array<T> 
    let limit: Int 

    func testMethod() { 
     let dict = [["id": "asd123"],["id":"asd456"]] 
     let a = dict.flatMap(TR.init) 
     let b = a[0] 
     let c = T.myFunction(b) 
    } 
} 

所以我只好告訴編譯器T.TRS和TR一樣。

+0

你的回答是正確的,因爲你引入了兩個泛型'T'和'TR',但除了簡單地符合它們各自的協議之外,你說'TR'是'T'''' associatedtype''。他們之間的這種關係是你的問題代碼中缺少的東西。做得好! +1 – milos

+0

另外,你不需要將'TR'限制爲'Remotable',這是從後續的等式中推斷出來的 - 即這足夠了:struct MySearchResult ' – milos

+0

感謝米洛斯的解釋。 – Ionut

0

嘗試強制展開a[0],因爲函數需要參數類型爲T.TRS,您確定a[0]將符合協議Remotable

let c = a[0] as! T.TRS 
T.myFunction(c) 
+0

感謝您的建議。它的工作,但我不是一個強大的解放力量粉絲。 – Ionut

相關問題