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 trialMitch Little
11,870 PointsWhy does my dictionary return 'Optional'
Please see code below for my practice of Functions.
Why does the printer function for the dictionary say "Optional".
func dictionaryModifier(dictionaryToBeModified: [String: String], keyAdded: String, valueAdded: String) -> [String: String] {
var dictionaryOfStrings = dictionaryToBeModified
let key = keyAdded
let value = valueAdded
/* dictionaryOfStrings[value] = key Alternative: */ dictionaryOfStrings.updateValue(value, forKey: key)
return dictionaryOfStrings
}
var dictionaryFunctionChecker = ["HOLA": "Spanish", "HELLO": "English"]
dictionaryFunctionChecker = dictionaryModifier(dictionaryToBeModified: dictionaryFunctionChecker, keyAdded: "BONJOUR", valueAdded: "French")
print(dictionaryFunctionChecker["HOLA"])
2 Answers
Caleb Kleveter
Treehouse Moderator 37,862 PointsWhen you retrieve a value from a dictionary, it returns an an optional type because you might get nil (because the key does not exist). To get the actual value, you have to unwrap the value.
This might not make sense, but it explained in this course.
Mitch Little
11,870 PointsOkay, looks like I haven't quite got to that stage in the track yet. Thanks to the both of you!
wwyattw
10,389 Pointswwyattw
10,389 PointsDictionaries are optional type. In later course, this is explained in Optional.