A type mismatch issue with generic methods

Viewed 82

I have faced an issue and I think rather than trying to explain, showing it will be more effective.

I have this code and when I run it prints out this

struct One: Codable {}
struct Two: Codable {}

func test<T: Codable>(ofType: T.Type) {
    print(ofType)
}

var array = Array<Codable.Type>()

array.append(One.self)
array.append(Two.self)

array.forEach { (type) in
    print(type)
} // Outs: One\nTwo

test(ofType: One.self) // out: One
test(ofType: Two.self) // out: Two

However when I try to say;

array.forEach { (type) in
    test(ofType: type)
}

it throws

Cannot convert value of type 'Codable.Type' (aka '(Decodable & Encodable).Type') to expected argument type 'T.Type'

and adding test(ofType: type as! T.Type) throws those for the forEach and test itself accordingly

Type of expression is ambiguous without more context
Cannot find type 'T' in scope

I am trying to implement this because of token refresh. When the token is refreshing I cache the requests with related type which response will be parsed into.

private static var cachedRequests: [(Endpoint, Decodable.Type)]
class func makeRequest<T: Decodable>(to endpoint: Endpoint, decodeAsWrapped type: T.Type, completion: @escaping (Result<T, Error>) -> Void)

Any suggestions?

EDIT

I want to add another weird thing as follows:

func test<T: Codable>(ofType: T.Type) {
    array.append(ofType)
}

Above code is working just fine. I can append ofType to an array however can't use any item from that exact array as an input for ofType. Extremely unexpected thing for me.

1 Answers

Is this what you wanted ?

struct One: Codable {}
struct Two: Codable {}

func test(ofType: Codable.Type) {
    print(ofType)
}

var array = Array<Codable.Type>()

array.append(One.self)
array.append(Two.self)

array.forEach { (type) in
    print(type)
} // Outs: One\nTwo

test(ofType: One.self) // out: One
test(ofType: Two.self) // out: Two

array.forEach { (type) in
    test(ofType: type)
} // Outs: One\nTwo
Related