Swift compiler cannot allow correct overload of + operator for arrays in common function

I had several problems with the plus operator, so I decided to research and got the following minimal example. When i compile

func f<T>(t: T) -> [T] { return [t] + [t] } 

everything is good. The compiler selects this operator overload plus:

 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 the following:

 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, for example, 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 thing), but I wonder what the actual problem is. Is this a mistake in the compiler or what I don’t understand here? And what is [_] in the error message trying to tell me?

I also looked at AST, but with only the small 101 compilers, this 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 enabled

 $ 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 brackets to the operator (either ([t] + [t]) + [t] , or [t] + ([t] + [t]) ) also does not compile, and return (+)([t], [t]) + [t] does.

0
source share
1 answer

So, I did what Hamish suggested and filed SR-4304 . According to Jordan Rose, this is still a broken master. I will update this answer when there is news about the error.

0
source

Source: https://habr.com/ru/post/1257603/


All Articles