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

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.