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

Bjorn Chambless
STAFF
Bjorn Chambless
Treehouse Guest Teacher

dict[3]="value" & dict.updateValue("value",forKey:3) are equivalent for a dict of type [Int:String]. Quiz says false

Tested in Swift 2.2 If the key/value pair is missing, a key/value pair is created. If the key exists, the value is changed

1 Answer

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

This is false because updateValue(:forKey:) is a method which returns the old value assigned to that key, or nil if that key wasn't in dict.

Bjorn Chambless
Bjorn Chambless
Treehouse Guest Teacher

In the statements from the question, neither L-value is used. If they were used in assignments, I would agree with you.

Anjali Pasupathy
Anjali Pasupathy
28,883 Points

Just because the return value isn't used doesn't mean it isn't there. Consider the following code in a playground:

var dict: [Int:String] = [1:"value", 2:"value", 3:"someValue"]
dict[3] = "anotherValue"
dict.updateValue("value", forKey:3)

If you run this in a playground, you'll see that to the right of the second line, the new value ("anotherValue") is shown. However, to the right of the third line, the old value ("anotherValue") is shown. I'm not assigning the return value for dict.updateValue("value", forKey:3) to a constant or variable, but that return value is still created. It just doesn't have any reference to it, so Swift's garbage collection deals with it before we have the chance to use it.