Quick ambiguous reference to the member '=='

Is this a bug in the Swift 3 compiler? This is not ambiguous, it is ==two Strings.

It says:

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

In this example, the 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"
    }
}
+4
source share
2 answers

This is a misleading error message - the ambiguity actually lies in the closure expression you pass to map(_:), since Swift cannot infer the return type of a multi-line closure without any external context.

Thus, you can do the closure in one line using the ternary conditional operator:

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

Or simply supply the compiler with some explicit return type information map(_:):

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

let strs : [String] = things.filter { $0.id == "1"} .map { _ in
+6

, < :

let shortNames = names.myFilter { (name) -> Bool in
    return name.count < 4
}

@Hamish, , :

(name: String)

, , .

0

Source: https://habr.com/ru/post/1657889/


All Articles