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 Swift Closures Functions as First Class Citizens Functions as Parameters

Michael Southon
Michael Southon
1,951 Points

fatal error: unexpectedly found nil while unwrapping an Optional value

Hi,

I have a Storyboard with two labels (called firstSelectedDate and secondSelectedDate) and two buttons (called firstDate and secondDate) plus a UIDatePicker.

The two buttons send start and end dates from the UIDatePicker to the two labels. I also have an IB Action button (called calculateDays), which when pressed will calculate the difference between the end date and the start date and send the output to a label (called resultNumberOfDays).

But I've run into a problem: the calculateDays function is crashing with the error message: "fatal error: unexpectedly found nil while unwrapping an Optional value". I've searched up this error message and I understand I must safely unwrap one of my constants using the 'if let' statement, but I'm lost as to how to do that.

If anyone can help I will be sooo grateful. Thanks!

==============

@IBAction func calculateDays(sender: AnyObject) {

    let start = String(firstSelectedDate.text!)
    let end = String(secondSelectedDate.text!)

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"

    if let startDate:NSDate = dateFormatter.dateFromString.(start)!

        // fatal error: unexpectedly found nil while unwrapping an Optional value

    let endDate:NSDate = dateFormatter.dateFromString(end)! //
    let cal = NSCalendar.currentCalendar()


    let unit:NSCalendarUnit = NSCalendarUnit.NSDayCalendarUnit

    let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: []) // error: Use of unresolved identifier 'startDate'


    print(components)

}