Search code examples
swiftdatexcode11dateformatter

Xcode 11, swift. Dateformatter always return nil


I have a problem with converting value from String to Date in Swift.

It always returns nil. What am I doing wrong?

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: "2019-05-03")

Here is what is happening in the debugger in Xcode

enter image description here


Solution

  • Update:

    It would appear that it is a bug in Xcode. Trying your code in the viewDidLoad and setting a breakpoint causes the lldb description of the date to be nil, however it correctly prints the expected value out.

    lldb missing value

    You can see more about the bug at this SO post, thanks to OOPer for the link.

    Currently this bug is still occurring in Xcode 11.2-beta


    A couple of points

    Use .dateFormat instead of .format

    Use the correct quotation marks " instead of , also you should remove the space from your date format string.

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let date = dateFormatter.date(from: "2019-05-03")
    

    Image showing above code working in Playgrounds