Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Collections and Control Flow Dictionaries Recap: Dictionaries

Why are these two lines of code not equivalent?

The following code snippets are equivalent dict.updateValue("yetAnotherValue", forKey: 3) and dict[3] = "yetAnotherValue"

4 Answers

I'm no Swift buff, but...

dict.updateValue("yetAnotherValue", forKey: 3) 
vs
dict[3] = "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 ( [3] ) 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[3] = "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 ( [3] ) from the dict dictionary, This line of code would do that:

let value = dict[3]

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.

Definitely Agreed

Daniel Cohen
Daniel Cohen
5,785 Points

This question should have been updated by now... very confusing to be told you're wrong for something that's clearly right.