Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Introduction to Core Data Understanding the Core Data Stack The Managed Object Model

Charlie Thomas
Charlie Thomas
40,856 Points

Why is Pasan force unwrapping optionals? Is there a better way to do this when initialising Core Data?

class CoreDataStack {
    lazy var applicationDocumentDirectory: URL = {
       let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let endIndex = urls.index(before: urls.endIndex)
        return urls[endIndex]
    }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        let modelUrl = Bundle.main.url(forResource: "TodoList", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelUrl)!
    }()
}

Why not use a guard statement or an if let statement?

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

In this case, your app won't work you don't get the NSManagedObjectModel, so a crash would actually make the most sense. There might be a better way to fail, but because this isn't a production app, that fail is fine.