Adding explicit return to closure causes compiler error: A compiler bug?

我的未来我决定 提交于 2020-01-06 18:53:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!