Best way to solve ambiguous references to methods


(Rob Mayoff) #1

So I was playing around with Sequences, and I came across a problem I
haven't been able to solve in a decent way. I’ve reduced it to a simpler
example here:
let array : [Int] = [1, 2, 3]
let mapArray = array.map { $0 }
let flatArray = mapArray.flatten() // Error!
This last line of code prints the following error:
let flatArray = mapArray.flatten() // Error!
                ^~~~~~~~

There are two problems here, but neither is an ambiguous method reference.
One problem is in the compiler: it's giving a less-than-helpful error
message. The other problem is in your code: your mapArray is an Array<Int>,
and Int isn't a SequenceType. All of the candidate flatten methods require
the sequence element type (in this case, Int) to be at least a
SequenceType. That is, flatten only works on a sequence of sequences.

This works:

let array: [Int] = [1, 2, 3]
let mapArray = array.map { [ $0 ] }
// Note that the closure above returns Array<Int>, not just Int.
// Therefore mapArray is Array<Array<Int>>.
let flatArray = mapArray.flatten()