I was writing some Swift today and encountered a problem with generic type inference. I submitted this as a bug here, but I wanted to make sure it is in fact a bug, not something that is unavailable for a specific reason.
So anyways, let's say I have the following function:
func foo<T>(_ closure: ((T) -> Void) -> Void) {
print(type(of: T.self))
}
Calling the following infers the proper type for T, String:
foo { bar in
bar("Hello")
}
// Prints "String.Type"
The problem arises when bar is called an additional time within the closure:
foo { bar in // Error: Generic parameter 'T' could not be inferred
bar("Hello")
bar("World")
}
It seems to me that if Swift can infer the type for the single invocation case, it ought to be able to infer the type for the case with multiple invocations. While this can be resolved by explicitly stating the type of bar
as (String) -> Void
, this can get a bit unwieldy for longer type signatures.
Is there a reason why Swift finds the multiple invocations case ambiguous? Or is it just a bug?