Reputation: 389
I'm trying to call a generic function and i get this error:
Cannot explicitly specialize a generic function
My code:
public func parse<T: Codable>(request: HTTPRequestProtocol,
completion: @escaping (T?) -> Void) {
///....
}
//
parser.parse<Person>(request: request, onSuccess: { (codable) in
//Error: Cannot explicitly specialize a generic function
}
How can i fix it? Thanks
Upvotes: 2
Views: 1715
Reputation: 274650
There is this rule in Swift that you must not explicitly say (using <>
s) what the generic parameters of a generic method are. You must give clues to the type inference engine to let it figure the generic parameters out. In this case, you can annotate the type of closure parameter, so that the closure has a type of (Person) -> Void
. With this information, the compiler can figure the type of T
out.
parser.parse(request: request, onSuccess: { (codable: Person) in ... }
In other cases, you might have to take in an extra parameter of type T.Type
. For example, if your function only takes a type parameter and no value parameters:
func foo<T>() { ... }
In that case, you'd need to add an extra parameter:
func foo<T>(_ type: T.Type) { ... }
so that you can use it as:
foo(Person.self)
Upvotes: 8