簡體   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