我的代码如下所示:协议相关的类型和泛型
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