Search code examples
nsdateformatterswift

Variable 'dateFormatter' used before being initialized in iOS Swift


I am using NSDateFormatter in my project using Swift language.

I am getting following error:

Variable 'dateFormatter' used before being initialized

My code:

var date : NSDate = (NSDate.date())

var dateFormatter : NSDateFormatter

dateFormatter.dateFormat = "dd:mm:yyyy HH:mm:ss zzz"

Solution

  • Change just one line.

    You not initialise the NSDateFormatter

    change below line:

    var dateFormatter : NSDateFormatter = NSDateFormatter()
    

    Complete code:

    var date : NSDate = (NSDate.date())
    
    var dateFormatter : NSDateFormatter = NSDateFormatter()
    
    dateFormatter.dateFormat = "dd:mm:yyyy HH:mm:ss zzz"