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
swiftfun
4,039 PointsDictionary Quiz - Is it wrong?
The quiz says the following statement is FALSE:
"The following code snippets are equivalent:"
dict.updateValue("yetAnotherValue", forKey: 3)
and
dict[3] = "yetAnotherValue"
Why is it false? Given the context, both can be true. For instance in the following dictionary, both code snippets are TRUE.
var airportNumbers: [Int: String] = [
1: "LGA",
2: "HTR",
3: "MCO"
]
airportNumbers.updateValue("yetAnotherValue", forKey: 3)
airportNumbers[3] = "yetAnotherValue"
Please let me know your thoughts.
3 Answers
Tommy Choe
38,156 PointsSo they're similar but NOT equivalent. The updateValue function actually RETURNS the value that was previously stored for the associated key whereas the subscript notation does not. The subscript notation simply replaces the value.
Hope that helps.
swiftfun
4,039 PointsI assume the answer relies on the fact that the first snippet contains an "update" function. Nonetheless I still think, given the context, both expressions could be equivalents.
swiftfun
4,039 PointsStill did not quite get what "returns" means.
What does returning means? Does it store ot somewhere? Please provide a practical example when developing an app
Tommy Choe
38,156 PointsOk let me use the example that you provided.
Under the hood, when you invoke the updateValue method, the value stored in the previous key, "MCO" is first updated to the new value "yetAnotherValue". Then the method actually returns "MCO" so that you can store it a constant or variable like this:
let result = airportNumbers.updateValue("yetAnotherValue", forKey: 3)
print(result) //"MCO"
Now you have the old value stored in result. At this point you can let the user know what value got replaced etc. etc.
Caleb Kleveter
Treehouse Moderator 37,862 PointsCaleb Kleveter
Treehouse Moderator 37,862 PointsCan you post a link to the quiz?