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

Minh Pham
Minh Pham
724 Points

What is wrong with these two lines of code?

I think these two lines of code are equivalent, but the answer is no.

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

dict[3] = "yetAnotherValue"

Can someone explain me why?

1 Answer

Damien Watson
Damien Watson
27,419 Points

Hi Minh,

I believe that the first is replacing a value for the key === 3, where the second is replacing the item at the '3' index of the array.

var dict = [2:"abc",
    3:"def",
    4:"ghi",
    0:"jkl"
]

// Replace key of 3
dict.updateValue("yetAnotherValue", forKey: 3)
/*
dict = [2:"abc",
    3:"yetAnotherValue",
    4:"ghi",
    0:"jkl"
]
*/

// Replace index 3
dict[3] = "yetAnotherValue"
/*
dict = [2:"abc",
    3:"def",
    4:"ghi",
    0:"yetAnotherValue"
]
*/
kisu kim
kisu kim
11,691 Points

You must be confused between the dicitionary and the array syntax.