0

I am getting an error in Swift that I don't understand. Here is the code from my playground:

class Person : CustomStringConvertible
{

    let Name :String;
    let DoB :NSDate?

    init(name :String, dob :NSDate?)
    {
        Name = name;
        DoB = dob;
    }

    func age() -> Double {
        let now = NSDate();
        let age :Double = now.timeIntervalSinceDate(self.DoB!);

        return age;
    }

    var description : String {
        return "Name: \(Name), Age: \(self.age())";
    }

}

extension NSDate {
    static func dateFromComponents(year :Int, month :Int, day :Int) -> NSDate {
        let components = NSDateComponents();
        components.year = year;
        components.month = month;
        components.day = day;
        return components.date!;
    }
}

let helena = Person(name: "Helena", dob: NSDate.dateFromComponents(1986, month: 8, day: 10));
print(helena);
jtbandes
  • 115,675
  • 35
  • 233
  • 266
Ian Newson
  • 7,679
  • 2
  • 47
  • 80

2 Answers2

4

The documentation for the NSDateComponents date property:

Returns nil if the calendar property value of the receiver is nil or cannot convert the receiver into an NSDate object.

You have not set the date components' calendar, so .date is nil. Read the answers on this question for more about unwrapping optionals.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
1

Your problem is that

NSDate.dateFromComponents(1986, month: 8, day: 10)

returns nil.

You can solve that by creating a date object like this:

let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd"
let date = format.dateFromString("1986-08-10")!

and then pass it like this:

let helena = Person(name: "Helena", dob: date);
print(helena);

Using NSCalender

let components = NSDateComponents()
components.year = 2000
components.month = 8
components.day = 1
let calender = NSCalendar(calendarIdentifier:  NSCalendarIdentifierISO8601)
let date2 = calender!.dateFromComponents(components)

let helena2 = Person(name: "Helena", dob: date2);
William Kinaan
  • 28,059
  • 20
  • 85
  • 118