Crashalot
Crashalot

Reputation: 34513

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

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)
    }
}

Upvotes: 16

Views: 11773

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16827

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

Upvotes: 27

Crashalot
Crashalot

Reputation: 34513

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.

Upvotes: 0

Related Questions