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 Build a Playlist Browser with Swift Building the Music Library and Playlist Models Using a Playlist Instance

Todd Valentine
Todd Valentine
771 Points

Forced Unwrapping of Dictionary Items

Why did we force unwrap the Strings from the playlistDictionary and not the playlist["artists"] or playlist["backgroundColor"]?

for example:

let largeIconName = playlistDictionary["largeIcon"] as String!

let colorsDictionary = playlistDictionary["backgroundColor"] as [String: CGFloat]

Is there not the possibility that artists and backgroundColor might not exist in the playlistDictionary and will return nil?

2 Answers

The properties "artists" and "backgroundColor" were not declared as optionals, while all the other properties were. If they aren't optionals, you don't unwrap them. The declarations were as follows:

struct Playlist {
   var title: String?
   var description: String?
   var icon: UIImage?
   var largeIcon: UIImage?
   var artists: [String] = []
   var backgroundColor: UIColor = UIColor.clearColor()

There's no question mark in the artists or backgroundColor declarations. They are both initialized in their declarations, so it is not possible for them to have nil values.

However, accessing values in a dictionary returns them as optionals. That's why the colors are unwrapped in the rgbColorFromDictionary method.

Thanks! Very helpful, I had the same question.

You're welcome. Glad I could help.