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

Qiang Lan
Qiang Lan
1,383 Points

About dictionary.updateValue in Xcode Version 7.3.1 (7D1014)

Hi, I am using the Xcode Version 7.3.1 (7D1014). It seems dictionary.updatValue could not add a new key value pairs in this version. It shows me the "nil".

Im on the same version and it seems to be working fine.

var test = ["A": 123, "B": 345]
test.updateValue(5, forKey: "A")
test

3 Answers

Yes, you are right. It will return nil and its the expected behavior.

Documentation says like this

"Returns the value that was replaced, or nil if a new key-value pair was added."

var dict = [1: "someValue", 2: "anotherValue"]

dict.updateValue("yetAnoterValue", forKey: 3) ```

The dict.updateValue does return nil however, printing dict or dict[3] has the value
Dalisson Figueiredo
Dalisson Figueiredo
7,731 Points

Works fine like this:

var test = ["A" : 123, "B" : 123]

test["A"] //this line will print 123

test.updateValue(5, forKey: "A")

test["A"]  //this line will print 5
Qiang Lan
Qiang Lan
1,383 Points

Thanks for the answer.

Yes, it works only update an existed key value pair. But in the quiz, there are two Questions about dictionary.updateValue. For example,


The following code snippets are equivalent

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

and

dict[3] = "yetAnotherValue"


The answer is True. But I think it is false, right?

Qiang Lan
Qiang Lan
1,383 Points

The other example is


Given the following code:

var dict = [1: "someValue", 2: "anotherValue"]

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

What is the result?


The answer was Add a third key value pairs to the dictionary, while Xcode gave me "nil".