Range subscript is ambiguous

(J.E. Schotsman) #1

I hit the same mysterious compiler message today.

Just because an initializer exists doesn't mean Swift will do automatic type conversion for you.
Swift is not AppleScript.
You can't even do this:
let x:Int32 = 0
let y:Int = x

ArraySlice is conceptually different from Array. For example the first index of a slice need not be zero.

Jan E.


On May 15, 2016, at 7:00 PM, Neil Faiman wrote:

This function seems simple enough:

   func foo(a: [Int], n: Int) {
       var x : [Int] = a[0..<n]

But it doesn’t compile.

error: ambiguous subscript with base type '[Int]' and index type 'Range<Int>'

The oddity is that if I change the assignment to this

   var y : [Int] = Array(a[0..<n])

then the compiler is happy.

Shouldn’t it be able to do any necessary type inference from the fact that the expression is in a context where an array is required?