Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.