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?

Im having trouble understanding what I'm doing wrong in this example.

I don't understand the question and i don't think it was addressed in the video.

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

2 Answers

Stone Preston
Stone Preston
42,016 Points

task 2 states: Assign the value for key "UK" to a constant named ukCurrency.

you can access values for keys in dictionaries by using subscript syntax which means placing the key in between brackets after the name of the dictionary:

let someValue = someDict["someKey"] // returns the value for the key of "someKey" in someDict

you need to access the value in the currencies dict with a key of "UK".

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

let ukCurrency = currencies["UK"] // ukCurrency now has a value of "Pound"

see the Swift eBook for more information on accessing and modifying dictionaries

see Stone's answer

Stone Preston
Stone Preston
42,016 Points

although the above code may pass the challenge, it is not the desired way to do it. the task states Assign the value for key "UK" to a constant named ukCurrency. you need to use the key to obtain a value from the dictionary, not assign a string literal of "Pound".

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

let ukCurrency = currencies["UK"] // ukCurrency now has a value of "Pound"

// let ukCurrency = "Pound" // challenge wants you to access the value using a key for the dictionary

Oops, I did not see that UK currency is already in the dictionary. I thought that the challenge was asking to create a new string and append the value to the dict. I was surprised when it worked and ended the challenge abruptly too.