Reputation:
An init method for Person class looks like
init (id:int64, firstName:String, lastName:String, birthDay:NSDate?)
As you can see birthDay is an optional, because we don't always have the birthday.
The data comes from a SQLite database. A date type does not exist in SQLite so the date is represented as a string (which can be NULL). To convert that string to an NSDate I created an extension to NSDate :
extension NSDate: Value {
public class var declaredDatatype: String {
return String.declaredDatatype
}
public class func fromDatatypeValue(stringValue: String) -> NSDate {
return SQLDateFormatter.dateFromString(stringValue)!
}
public var datatypeValue: String {
return SQLDateFormatter.stringFromDate(self)
}
}
So when creating a person:
let person = Person(id: row[id], firstName: row[first_name], lastName: row[last_name], birthDay:NSDate.fromDatatypeValue(row[birthday]!))
will fail if the birthday string is NULL. (I have to unwrap the row[birthday]! as expects a non-optional String, and this may/can not be changed)
So my idea was to test for this before creating the person
var birthday : NSDate
if let birthdayString = row[Person.birthday] {
birthday = NSDate.fromDatatypeValue(birthdayString)
} else {
birthday=nil
}
and the use birthday in the init function.
BUT swift tells me : Cannot assign a value of type 'nil' to a value of 'NSDate'
How can this be solved ?
PS. : I know I could have an if and 2 initializers but I'd rather not have as my Person init func has 12 parameters (for reasons of simplicity I've only used 4 above) and maintaining this is a pita
Upvotes: 4
Views: 6114
Reputation: 2452
Do the following.
var birthday : NSDate? = nil
if let birthdayString = row[Person.birthday] {
birthday = NSDate.fromDatatypeValue(birthdayString)
}
Upvotes: 8