Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Ambiguous use of prefix" compiler error with Swift 3

Tags:

xcode8

swift3

I just migrated my project from Swift 2.2 to Swift 3.0 with Xcode 8 beta.

I have something similar to the following code (you can paste this into a playground):

import Foundation

let datesWithCount: [(Date, Int)] = [(Date(), 1), (Date(), 2), (Date(), 3)]

let dates: [Date] = datesWithCount.sorted {
    $0.0 < $1.0
}.prefix(1).map {
    return $0.0
}

In Swift 2.2 this compiled fine. However, with Swift 3.0 I get the error

Ambiguous use of 'prefix'

The only way to get this to compile in Swift 3.0 is to split out the map into a separate line:

let sortedDatesWithCount = datesWithCount.sorted {
    $0.0 < $1.0
}.prefix(1)

let mappedDates = sortedDatesWithCount.map {
    return $0.0
}

BTW, in the actual code I'm returning NSNotification objects from the map not Dates but the error is the same. I just used Date here for making the example simple.

Is there any way to get this to compile as a one liner?

UPDATE: Created a JIRA for the Swift project.

like image 346
mluisbrown Avatar asked Jun 20 '16 20:06

mluisbrown


1 Answers

It works if you make the ArraySlice into an Array before passing it to map:

let dates: [Date] = Array(datesWithCount.sorted {
    $0.0 < $1.0
}.prefix(1)).map { return $0.0 }

This looks like a type inference bug in the compiler.

like image 67
Eric Aya Avatar answered Nov 12 '22 23:11

Eric Aya