What is this type of code used with dateFormatter called and why is it used over regular style?

In your book, you’ve used this type of code which while clean, messes up a bit with autocomplete.
lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()

Instead of that you could do:
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle =.medium

Is this preferable way to do?

It’s also used in CoreDataStack this way:
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores {
(storeDescription, error) in
if let error = error as NSError? {
print(“Unresolved error (error), (error.userInfo)”)
}
}
return container
}()

Thanks.

@thesharad96 Thanks very much for your question. While the code you provided may work, the reason using lazy variables is a better approach is that this allows you to be more efficient in using your objects, so that you’re creating them when you actually NEED to use them (when the object is first requested), as opposed to creating them right at the very beginning, and letting them consume resources on your device that could be better used elsewhere. Think of lazy variables as creating objects “just in time”. Building an app that is functioning efficiently means your app will optimize your devices resources better, which in turn means a better user experience. This is especially important with Core Data because it can be a quite expensive framework to use inside your app, if not used properly.

I hope this helps! :slight_smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.