Swift编译器无法解析泛型函数中数组的+运算符的正确重载 [英] Swift compiler unable to resolve correct overload of + operator for arrays in generic function
问题描述
我在使用plus运算符时遇到了几个问题,因此我决定进行调查,最后得到了以下最小示例.当我编译
I've had several problems with the plus operator so I decided to investigate and ended up with the following minimal example. When I compile
func f<T>(t: T) -> [T]
{
return [t] + [t]
}
一切都很好.编译器选择加号运算符的这种重载:
everything is fine. The compiler chooses this overload of the plus operator:
public func +<RRC1 : RangeReplaceableCollection, RRC2 : RangeReplaceableCollection
where RRC1.Iterator.Element == RRC2.Iterator.Element>
(lhs: RRC1, rhs: RRC2) -> RRC1
但是,当我在游戏中添加另一个+
时,我会得到:
However, when I add another +
to the game, I get this:
func f<T>(t: T) -> [T]
{
return [t] + [t] + [t]
}
main.swift:30:9: error: cannot convert value of type '[T]' to expected argument type '[_]' (aka 'Array<_>')
return [t] + [t] + [t]
^~~
as! [_]
我找到了几种方法来完成这项工作,例如return ([t] as [T]) + [t] + [t]
或这样:
I found several ways to make this work, like for instance return ([t] as [T]) + [t] + [t]
, or this:
func f<T>(t: T) -> [T]
{
let t1 = [t]
return t1 + [t] + [t]
}
(可能基本相同),但我想知道实际的问题是什么.这是编译器中的错误吗?
还是我在这里不明白什么?错误消息中的[_]
试图告诉我什么?
(which is probably essentially the same) but I wonder what the actual problem is. Is this is a bug in the compiler
or what am I not understanding here? And what is the [_]
in the error message trying to tell me?
我也查看了AST,但是,由于只有浅浅的Compilers 101知识,这似乎证实了我的直觉,即编译器无法 找到加号运算符的正确版本.
I've also looked at the ASTs but, having only shallow Compilers 101 knowledge, this just seems to confirm my hunch that the compiler is unable to find the correct version of the plus operator.
我正在使用随附的Xcode 8.2.1(8C1002)
I am using Xcode 8.2.1 (8C1002) with the included
$ swift --version
Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)
Target: x86_64-apple-macosx10.9
更新
我忘了在语句(([t] + [t]) + [t]
或[t] + ([t] + [t])
)上加上括号也不会编译,而return (+)([t], [t]) + [t]
会编译.
I forgot that adding parentheses to the statement (either ([t] + [t]) + [t]
or [t] + ([t] + [t])
) doesn't compile either, while return (+)([t], [t]) + [t]
does.
推荐答案
So I did what Hamish suggested and filed SR-4304. According to Jordan Rose this is still broken in master. I will update this answer when there is any news on the bug.
这篇关于Swift编译器无法解析泛型函数中数组的+运算符的正确重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!