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
Chung-En Hsu
3,761 Pointsfatal error: unexpectedly found nil while unwrapping an Optional value
The system highlights the following codes:
playlist.backgroundColor = playlistImageView.backgroundColor!
I know the exclamation mark at the end of this sentence was different from that of the video, but it was suggested by my Xcode.
Can't think of what went wrong...Can someone plz help me with this problem? Thanks a lot!!!
2 Answers
Jason Wayne
11,688 PointsChung-En Hsu - Cool! Glad it worked
Jason Wayne
11,688 PointsThe reason why you are seeing this is because you are force unwrapping a nil value. You should only do it if you're 100% sure that the value is always present. Best practice is to never do this at all by your own. Always try to do optional chaining or guard to safely unwrap an optional.
Xcode is probably recommending that because the backgroundColor attribute is an optional. To read an optional value, one must be unwrapped. However, Xcode will not provide you with the safe unwrap option, which is what you would need to do instead.
Perhaps, checking to see if playlistImageView and it's attribute is nil or not before assignment will help
Chung-En Hsu
3,761 PointsThank you very much!!!!!! I safely unwrapped the backgroundColor as follows and it's all good now:
if let playlistImageViewBackgroundColor = playlistImageView.backgroundColor { playlist.backgroundColor = playlistImageViewBackgroundColor }