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

Adding a key-value pair

To add a new key-value pair to a dictionary, we can use the subscript syntax or the same updateValue(_:, forKey:) method that we used to update the value of a key. If we use the updateValue(_:, forKey:) method and the key is not currently present in the dictionary, this method will add a new key-value pair and return nil. The following example shows how to use both the subscript syntax and the updateValue(_:, forKey:) method to add a new key-value pair to a dictionary:

var countries = ["US":"United States", "IN":"India","UK":"United Kingdom"] countries["FR"] = "France" //The value of "FR" is set to"France" var orig = countries.updateValue("Germany", forKey: "DE") //The value of "DE" is set to "Germany" and orig is ...

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