My code looks like this:
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
}
}
And I cannot get to call myFunction because it expects a T.TRS type of argument. I was expecting that I can call myFunction with the b parameter that is of type TR. Do you have any idea of what am I doing wrong?
I also found an answer to my own question. I don't know which one is better, I would be grateful if someone would explain which is better and why.
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)
}
}
So I just had to tell the compiler that T.TRS is the same as TR.
Try to force unwrap a[0]
as the function expects an argument of type T.TRS
, you are sure that a[0]
will conform to protocol Remotable
.
let c = a[0] as! T.TRS
T.myFunction(c)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.