[swift-users] Best way to solve ambiguous references to methods

Rob Mayoff mayoff at dqd.com
Sat Dec 5 12:35:03 CST 2015


>
> 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()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151205/82fa9425/attachment.html>


More information about the swift-users mailing list