Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Ambiguous reference to member map" when attempting to append/replace array element

Tags:

swift

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)
    }
}
like image 607
Crashalot Avatar asked Dec 19 '15 08:12

Crashalot


1 Answers

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

like image 50
Knight0fDragon Avatar answered Nov 06 '22 10:11

Knight0fDragon