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 Collections and Control Flow Dictionaries in Swift Modifying a Dictionary

Sebastian Eguez
Sebastian Eguez
8,248 Points

What is the difference between updateValue and...

// Dictionaries

/*

        Airport Code (Key)      Airport Name (Value)

        LGA                     La Guardia
        LHR                     Heathrow
        CDG                     Charles de Gaulle
        HKG                     Hong Kong International
        DXB                     Dubai International

*/

// ["LGA": "La Guardia", "LHR": "Heathrow", "CDG": "Charles de Gaulle", "HKG": "Hong Kong International", "DXB": "Dubai International" // You can also write this like BELOW

var airportCodes: [String: String] =
[
    "LGA": "La Guardia",
    "LHR": "Heathrow",
    "CDG": "Charles de Gaulle",
    "HKG": "Hong Kong International",
    "DXB": "Dubai International"
]

let currentWeather = ["Temperature": 75.0] // Press the option button and hover over currentWeather

// Reading from a dictionary

airportCodes["LGA"]
airportCodes["HKG"]

// Inserting Key Value Pairs

airportCodes["SYD"] = "Sydney Airport" // airportCodes needs to be a var to insert a key value pair
airportCodes["LGA"] = "La Guardia International Airport"
airportCodes["LGA"]
airportCodes.updateValue("La Guardia Airport", forKey: "LGA")

What is the difference between changing "LGA": "La Guardia" using

airportCodes["LGA"] = "La Guardia International Airport"

and

airportCodes.updateValue("La Guardia Airport", forKey: "LGA")

?

Why and when should you use one or the other?

Thanks.

1 Answer

Matt Skelton
Matt Skelton
4,548 Points

Hey Sebastian,

I started typing an explanation for the advantages of using each, and then I stumbled upon this in the Apple documentation.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID113

Take a look at the section under "Accessing and Modifying a Dictionary", it covers your question with examples and describes it much better than I could!

mrtroy
mrtroy
8,069 Points

The Apple documentation did a good job of explaining how to use the Dictionary but I am still wondering if the method way is better then an assignment. It does have more options but does it conserve CPU time or space?