Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift ambiguous reference to member '=='

Tags:

swift

swift3

Is this a bug in Swift 3 compiler? It's not ambiguous, it's == and two Strings.

It says:

error: ambiguous reference to member '=='
let strs = things.filter { return $0.id == "1" } .map { t in
                                        ^~

For this example code:

class Thing {
    var id: String = ""
}
let things = [Thing]()
let x = 1
let strs = things.filter { return $0.id == "1" } .map { t in
    if x == 1 {
        return "a"
    }
    else {
        return "b"
    }
}
like image 913
Rob N Avatar asked Oct 15 '16 23:10

Rob N


1 Answers

It's a misleading error message – the ambiguity actually lies with the closure expression you're passing to map(_:), as Swift cannot infer the return type of a multi-line closure without any external context.

So you could make the closure a single line using the ternary conditional operator:

let strs = things.filter { $0.id == "1"} .map { _ in
    (x == 1) ? "a" : "b"
}

Or simply supply the compiler some explicit type information about what map(_:) is returning:

let strs = things.filter { $0.id == "1"} .map { _ -> String in

let strs : [String] = things.filter { $0.id == "1"} .map { _ in
like image 79
Hamish Avatar answered Nov 11 '22 12:11

Hamish