O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Updating the value of a key

To update the value of a key in a dictionary, we can use either the subscript syntax or the updateValue(_: ,forKey:) method. The updateValue(_:, forKey:) method has an additional feature that the subscript syntax doesn't: it returns the original value associated with the key prior to changing the value. The following example shows how to use both the subscript syntax and the updateValue(_:, forKey:) method to update the value of a key:

var countries = ["US":"United States", "IN":"India","UK":"United Kingdom"] 
 
countries["UK"] = "Great Britain" 
//The value of UK is now set to "Great Britain" 
 
var orig = countries.updateValue("Britain", forKey: "UK") 
//The value of UK is now set to "Britain"//The orig variable equals ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required