16

Several SO posts like this deal with the same error message, but none of those solutions work. It appears like this could be a case of a misleading error message.

The code below generates an "Ambiguous reference to member map" error for the map call.

Anyone know why?

func saveUser(user: User) {
    var userDicts = masterDict["users"] as! [[String:AnyObject]]
    let newDict = user.getDict()

    // Replace matching element with <newDict>
    let replaced = false
    masterDict["users"] = userDicts.map {
        if ($0["id"] as String! == user.getId()) {
            replaced = true
            return newDict
        } else {
            return $0 as [String:AnyObject]
        }
    }

    // If no match found, means must add new user
    if (!replaced) {
        userDicts.append(newDict)
    }
}
Community
  • 1
  • 1
Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • It seems like swift is having a hard time inferring type for map. try `userDicts.map {val -> [String:AnyObject] in` and swap out `$0` for `val` – Knight0fDragon Dec 19 '15 at 09:38
  • Also, what version of Xcode are you using, I can't seem to replicate your exact error, and the first error I see is "change replaced to a var", so maybe you need to update Xcode. I am currently on 7.2 – Knight0fDragon Dec 19 '15 at 09:45
  • It's not the main problem but `replaced` should be a `var` not a `let` – Luca Angeletti Dec 19 '15 at 15:21
  • @Knight0fDragon sorry, you're right. this was a sanitized version and forgot to replace the `let` for `replaced` but everything else is the same. Using Xcode 7.2. – Crashalot Dec 19 '15 at 21:07

2 Answers2

27

Unfortunately, swift is not perfect and can not infer types at all times, this is why you are getting the ambiguous reference. Try userDicts.map {val -> [String:AnyObject] in and swap out $0 for val This will explicitly tell the map that the values coming in are [String:AnyObject], and should be able to return said type

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • Do you also happen to know the answer to this other question: http://stackoverflow.com/questions/34376729/modifying-dictionary-property-inside-of-array-of-dictionaries-error-cannot-ass/34378199#34378199. Thanks! – Crashalot Dec 20 '15 at 20:46
0

Never isolated the cause of the error so switched to using a for loop, creating a new array inside the loop, and calling masterDict["users"] = newArray after the loop. Not the cleanest, but it fixes the error.

Crashalot
  • 33,605
  • 61
  • 269
  • 439