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 Recap: Dictionaries

Sebastian Shelley
Sebastian Shelley
1,388 Points

How come these two statements aren't equivalent?

Can somebody please explain to me how these two statements aren't equivalent?

The following code snippets are equivalent

dict.updateValue("yetAnotherValue", forKey: 3)

and

dict[3] = "yetAnotherValue"

Iโ€™ve tried both statements in code and created a new Dictionary to match and they both seem equivalent. However in the quiz the answer is they are not equivalent.

1 Answer

Hey Sebastian! From the Swift language reference:

"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."

Hope that helps!

Sebastian Shelley
Sebastian Shelley
1,388 Points

Thanks a lot that really helped.