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
Cory Sovilla
11,087 PointsIs it possible to have a Dictionary have a Tuple as a value?
In my code I have a Dictionary that contains a tuple for its value but I am having trouble calling the values inside the tuple.
For example,
var testingCode: [String:(Int,Bool)] = [ "Joe":(41,true),"Bob":(36,false)]
How would I go about getting the values of 41 and true from Joe?
I get an Error when I type
testingCode["Joe"].0 or testingCode["Joe"].1 and the error tells me to put a !(Optional) as follows:
testingCode["Joe"]!.0 // I dont understand why it wants the !
Is there a way to make it where the ! is not needed?
1 Answer
Martin Wildfeuer
Courses Plus Student 11,071 PointsThis is intended behavior of a dictionary and has nothing to do with the values being tuples. Getting a value from a dictionary will always return an optional, as it is possible that the key (and therefore the value) do not exist. For example, with this code
let testingCode: [String:(Int,Bool)] = [ "Joe":(41,true),"Bob":(36,false)]
let test = testingCode["Anna"] // using ! here would crash the app
test would be nil, as the key does not exist. In order to handle this scenario correctly, you have to unwrap the optional. Never, I repeat, never force unwrap this with ! as this will crash your app in case the key does not exist. Force unwrapping basically works against Swifts great safety introduced with optionals. Make yourself familiar with the concept of optionals, a good resource are the Apple Docs.
So, here is an example on how to do it
let testingCode: [String:(Int,Bool)] = [ "Joe":(41,true),"Bob":(36,false)]
// Unwrapping
if let test = testingCode["Joe"] {
print(test.0)
}
// Alternatively, unwrapping with guard
guard let test = testingCode["Joe"] else {
return
}
print(test.0)
Hope that helps :)