Hi
When creating Core Data iOS project we get the below code, I find it strange to declare a variable then making it equal to a code ? or a result of a code without function calling ?
--
Kindest Regards
static var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CoreDataApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
What you do is have a closure ; adding () at the end, you execute the code of the closure. And get the value by return. This is what you store to the var.
You could have written
let myClosure = { let container = NSPersistentContainer(name: "CoreDataApp")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
/* store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}
static var persistentContainer: NSPersistentContainer = myClosure()
Then it would be clearer:
- myClosure is a closure
- var is NSPersistentContainer