我的代碼如下所示:協議相關的類型和泛型
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。你有什麼想法我做錯了什麼?
你的回答是正確的,因爲你引入了兩個泛型'T'和'TR',但除了簡單地符合它們各自的協議之外,你說'TR'是'T'''' associatedtype''。他們之間的這種關係是你的問題代碼中缺少的東西。做得好! +1 – milos
另外,你不需要將'TR'限制爲'Remotable',這是從後續的等式中推斷出來的 - 即這足夠了:struct MySearchResult' –
milos
感謝米洛斯的解釋。 – Ionut