问题
Consider this generic method (only the types are important, not what it does):
func flatMap<SourceType, TargetType>(source: [SourceType], transform: SourceType [TargetType]) -> [TargetType] {
return []
}
Following call to the method compiles nicely:
let seq = flatMap(["some", "string"], { s in [1, 2] })
However, just adding explicit return to closure cases compile error:
let seq = flatMap(["some", "string"], { s in return [1, 2] }) //ERROR: Cannot convert the expression's type ... to type 'StringLiteralConvertible'
The compiler can still infer the types in the same way it did it in first case, right? Where is the difference (I cannot see any)? How can I make the second case compile if I need that return
in place?
回答1:
It works if you make the return type of the closure explicit:
let seq = flatMap(["some", "string"], { s -> [Int] in return [1, 2] })
What is interesting is that it only happens if the generic value isn't defined anywhere else. So the sorted closure of an array doesn't have this issue:
[1,2,3].sorted{a,b in return a < b} //works
And if you, for some reason, add a parameter to function with the TargetType, it also works:
func flatMap<SourceType, TargetType>(source: [SourceType],aTarget:TargetType, transform: SourceType -> [TargetType]) -> [TargetType] {
return []
}
let seq = flatMap(["some", "string"], 1, {s in return [1, 2]}) //works
It's either a compiler bug or a way to force things to be more explicit in potentially ambiguous situations.
来源:https://stackoverflow.com/questions/26305402/adding-explicit-return-to-closure-causes-compiler-error-a-compiler-bug