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 Enumerations and Optionals in Swift Introduction to Optionals Nil Values in Collections

Aryaman Dhingra
Aryaman Dhingra
3,536 Points

How to get optional values from nested dictionaries?

I don't understand optional values very well, I just need some clarification on how to get optional values from the nested dictionaries. I would also like to know what I am doing wrong.

optionals.swift
let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "LÊa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]

var leadActor: String = ""

// Enter code below

if let movieCast = movieDictionary["Spectre"], let movieFullCast = movieCast["cast"] {
  print(movieFullCast[0])
  }

2 Answers

tromben98
tromben98
13,273 Points

Hi!

You are just printing the lead actor instad of assigning it to the leadActor property.

Here is the solution:

let movieDictionary = ["Spectre": ["cast": ["Daniel Craig", "Christoph Waltz", "LÊa Seydoux", "Ralph Fiennes", "Monica Bellucci", "Naomie Harris"]]]

var leadActor: String = ""

// Enter code below
if let movie = movieDictionary["Spectre"],
let cast = movie["cast"] {
leadActor = cast[0]
}
Daniel Walkowski
Daniel Walkowski
549 Points

You are not checking for the implicit optionals. All dictionaries and Arrays contain Optional keys/elements. If I am incorrect, please enlighten me.
I'd like to see an optional chaining solution. I'm trying to write one now