2016-03-31 114 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

相关问题