Why isn't special version of generic being called?

private func decodeResponse(data: Data, response: HTTPURLResponse) throws -> Data {
    print("In special data decode")
    return data
}

private func decodeResponse<T>(data: Data, response: HTTPURLResponse) throws -> T {
    print("In generic version, type: ", T.self)
    ...
    return <something of type T>
}

   let value: Data = decodeResponse(...)   // should call first version?

In actual fact, the first call invokes the generic function, and prints "In generic version, type: Data".

But I expected to see "In special data decode" printed.

I've tried this in simple tests and it works. What might I be doing wrong?

1 Like

Answering my own question: in my simple tests, I invoke decodeResponse() from a non-generic function (like you see in my post). In a real example (which doesn't work) I was invoking it from a generic function and thinking it would be smart enough to pick the overload I wanted. I guess it doesn't work that way...

I needed to create a specialized version of my caller, as well.

1 Like

Correct; overload resolution happens at compile time. If you would like to resolve via dynamic dispatch it has to either go through a protocol requirement or subclass override.

2 Likes

In generic context you can make a function call specifying type explicitly:
self.decodeResponse(data: data, response: urlResponse) as Data

You are not doing something wrong, this is just how overload resolution works.