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

Liam George
Liam George
12,004 Points

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

In the line "let coloursDictionary = playlistDictionary["backgroundColour"] as [String: CGFloat]" is comes back saying "fatal error: unexpectedly found nil while unwrapping an Optional value" I don't know how to fix it.

import Foundation
import UIKit

struct Playlist {

    var title: String?
    var description: String?
    var icon: UIImage?
    var largeIcon: UIImage?
    var artists: [String] = []
    var backgroundColour: UIColor = UIColor.clearColor()

    init(index: Int) {
        let musicLibrary = MusicLibrary().library
        let playlistDictionary = musicLibrary[index]

        title = playlistDictionary["title"] as String!
        description = playlistDictionary["description"] as String!

        let iconName = playlistDictionary["icon"] as String!
        icon = UIImage (named: iconName)

        let largeIconName = playlistDictionary["largeIcon"] as String!
        largeIcon = UIImage(named: largeIconName)

        artists += playlistDictionary["artists"] as [String]

        let coloursDictionary = playlistDictionary["backgroundColour"] as [String: CGFloat]

        backgroundColour = rgbColourFromDictionary(coloursDictionary)
    }

    func rgbColourFromDictionary(colourDictionary: [String: CGFloat]) -> UIColor {

        let red = colourDictionary["red"]!
        let green = colourDictionary["green"]!
        let blue = colourDictionary["blue"]!
        let alpha = colourDictionary["alpha"]!

        return UIColor(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: alpha)

    }
}

1 Answer

Jared Watkins
Jared Watkins
10,756 Points

The problem is that the provided code for the MusicLibrary Struct uses the key "backgroundColor" spelled the American way as 'color. Changing the key to 'backgroundColor' should fix it for you (although I had to change the spelling of 'color' to 'colour' in the the master and detail view controllers to get your code to work for me).

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

Hope this fixes it for you.