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

Why 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"])

Dictionaries are optional type. In later course, this is explained in Optional.

2 Answers

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

When 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.

Okay, looks like I haven't quite got to that stage in the track yet. Thanks to the both of you!