Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Collections and Control Flow Dictionaries Modifying a Dictionary

Is there a reason to use the updateValue method vs. just typing airportCodes["LGA"] = "La Guardia International Airport?

It seems to do the same thing. Why would we want to type more?

1 Answer

Here's what the Apple documentation says is the difference:


You can also use subscript syntax to change the value associated with a particular key:

airports["LHR"] = "London Heathrow" // the value for "LHR" has been changed to "London Heathrow"

As an alternative to subscripting, use a dictionary’s updateValue(:forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(:forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(_:forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.


I.e., the difference is that updateValue() returns the old value.