对闭包添加显式返回会导致编译器错误:编译器错误? [英] Adding explicit return to closure causes compiler error: A compiler bug?

查看:187
本文介绍了对闭包添加显式返回会导致编译器错误:编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个泛型方法(只有类型很重要,而不是它的作用):

Consider this generic method (only the types are important, not what it does):

func flatMap<SourceType, TargetType>(source: [SourceType], transform: SourceType [TargetType]) -> [TargetType] {
    return []
}

compiled nicely:

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'

编译器仍然可以以相同的方式它做到了第一种情况,对吧?差别在哪里(我看不到任何)?如果我需要 return ,那么如何使第二种情况编译?

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?

推荐答案

如果你使得闭包的返回类型是显式的,它会工作:

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.

这篇关于对闭包添加显式返回会导致编译器错误:编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆