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!
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
Why are these two lines of code not equivalent?
The following code snippets are equivalent dict.updateValue("yetAnotherValue", forKey: 3) and dict = "yetAnotherValue"
I'm no Swift buff, but...
dict.updateValue("yetAnotherValue", forKey: 3) vs dict = "yetAnotherValue"
The first is updating a value in the dictionary variable "dict" In the first, it's calling the method updateValue, which takes a value to set (to update) at a specified key. In the first line, it's setting the value at key 3 (forKey: 3) to "yetAnotherValue"
The second method is just returning the value at the third positions (  ) from the dict dictionary, and setting that location equal to "yetAnotherValue". They are just two different ways to get the same result.
I am not sure the benefits or drawbacks of either approach, but they achieve the same result.
Hope that helps!
Chang, the challenge is wrong. Good eyes! They do exactly the same thing. You should report the error.
Consider this code. If you put it in an Xcode playground, it will display what I've shown in the comments:
var dict = [1: "Hello", 2: "Good Bye", 3: "X"] //[2: "Good Bye", 3: "X", 1: "Hello"] dict.updateValue("yetAnotherValue", forKey: 3) //"X" dict //[2: "Good Bye", 3: "yetAnotherValue", 1: "Hello"] dict = "yetAnotherValue2" //"yetAnotherValue2" dict //[2: "Good Bye", 3: "yetAnotherValue2", 1: "Hello"]
Re what they do, both are setting the value of the pair with the key of 3 to a new value. So the first changes the pair 3: "X" to 3: "yetAnotherValue", and the second changes 3: "yetAnotherValue" to 3: "yetAnotherValue2"
P.S., the second is not returning the value at the third positions (  ) from the dict dictionary, This line of code would do that:
let value = dict
Thanks for the comments, David and JCorum! Guess we all agree the results to dictionary dict are the same. From that angle, these two lines of code should be consider as equivalent, as there is no other side effect.
Daniel Cohen5,785 Points
This question should have been updated by now... very confusing to be told you're wrong for something that's clearly right.