moka2258 moka2258 - 1 year ago 82
Swift Question

Why does NSDateFormatter not return nil when given empty string ("")

I have a quick question.
According to apple official documentation

NSDateFormatter.dateFromString(String) would return

A date representation of string interpreted using the receiver’s current settings. If dateFromString: can not parse the string, returns nil.

Then I when I give it an empty string "", should it return nil?
When I do this in the playground

let date = ""
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyyMMdd"

It gave me

"Optional(1999-12-31 15:00:00 +0000)\n"

Is this happen to be a normal behaviour?
Or am I doing something wrong?

Thank you

Answer Source

If dateFromString: can not parse the string, returns nil

The simple answer is, the dateFromString does manage to parse an empty string. If you try and put wrong data in the string, say "0" then you will get nil.

Why is it happening? I assume that it is just they way the class is written, since the date formatter does skip missing data and try to complete it. There is probably not a case for "all is missing".