Swift compiler unable to resolve correct overload

2019-09-18 09:13发布

问题:

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! [_]

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?

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.

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

Update

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.

回答1:

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.