Updating values

It appears that in the past, Bob was caught cheating when playing cards. He’s not just a professional, he’s a card shark! He asks you to change his name and profession so no one will recognize him.

Because Bob seems eager to change his ways, you agree. First, you change his name from Bob to Bobby:

bobData.updateValue("Bobby", forKey: "name")

// > Bob

You saw this method above when you read about adding pairs. Why does it return the string Bob? updateValue(_:forKey:) replaces the value of the given key with the new value and returns the old value. If the key doesn’t exist, this method will add a new pair and return nil.

As with adding, you can do this with less code by using subscripting:

bobData["profession"] = "Mailman"

Like updateValue(_:forKey:), this code updates the value for this key or, if the key doesn’t exist, creates a new pair.

results matching ""

    No results matching ""