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 Basics (retired) Collections What is a Dictionary?

Fernando Benavides
Fernando Benavides
1,554 Points

Challenge Task 2 of 2

What have I do exactly in Challenge Task 2 of 2? I can't understand

dictionaries.swift
let currencies = ["US":"Dollar","UK":"Pound","JP":"Yen"]
let ukCurrency = ["Pound"]

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Hello, Kyle Vandeven and Fernando Benavides

Yes, there're different ways of approaching the problem, but for this particular code challenge.

Assign the value for key "UK" to a constant named ukCurrency.

You should be using dictionary key lookup to retrieve the value from currencies dictionary.

let ukCurrency = currencies["UK"]

There're several disadvantages of hard coding the value "pound" to the ukCurrency constant VS using dictionary key-lookup.

  • it defeats the purpose of using a dictionary data structure.
  • for this code, the currencies dictionary is small, containing merely 3 entries, if however it has hundreds of thousands entries stored in an unordered fashion, it'd take you quite a while to scan through the collection to find the value associated with a particular key.
  • if some point in the future, UK decides to join the EU, and changes its currency to Euro, you'd have to change your code in both lines, whereas in using the key-lookup, we only need to change the code in one place.

Hope this helps.

There are probably multiple ways of passing this challenge, but to assign the value for the key "UK" (which is "pound") to a constant named ukCurrency, it is as simple as

let ukCurrency = "Pound"

So the complete code would be:

let currencies = ["US":"Dollar","UK":"Pound","JP":"Yen"]
let ukCurrency = "Pound"