Adding, Removing, and Inserting with Dictionaries
Previously you used the subscript syntax (the square brackets syntax) to access elements of a dictionary. You can use that syntax to also set values by key. In the previous example, you can set a person with a Social Security number of 384958338:
people[384958338] = "Skip Wilson"
If the key exists, then you will replace that Social Security value with Skip Wilson
. If not, you will have a new key/value pair. Try to assign a key using a string, and you get an error.
You can also use the method updateValue(forKey:)
to update your dictionary. This method also updates a value for a key if it exists, or it creates a new key value if it does not exist. updateValue
returns ...
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.