繁体   English   中英

协议关联类型和泛型

[英]Protocol associated types and generics

我的代码如下所示:

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。 你知道我做错了什么吗?

我也找到了我自己问题的答案。 我不知道哪个更好,如果有人能解释哪个更好以及为什么,我将不胜感激。

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 相同。

尝试强制解包a[0]因为该函数需要一个类型为T.TRS的参数,您确定a[0]将符合协议Remotable

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM