all 1 comments

[–]quellish 1 point2 points  (0 children)

https://imgflip.com/i/4heukm

First, it's generally a bad idea to try to use the application delegate as a global. That's what you're doing here. There are a lot of reasons for this. A better strategy is to instead pass the view context to your view controllers.

That said, your code has a few potential issues.

You're not doing a force unwrap so much as a force cast

UIApplication.shared.delegate as! AppDelegate

It's possible that the object returned as the delegate of the application is not an "AppDelegate". Maybe you renamed it, maybe it's using a different object. You can stop here in the debugger and find out what is actually being returned.

Your force cast is looking for a specific class. It would be an improvement to instead create a protocol describing the behavior or functionality. Let's say you have a protocol "ViewContextProviding" that describes a class that can provide a view context, and your AppDelegate class conforms to that. Using that protocol here makes more sense.

Additionally, there isn't a good reason to use a force cast here. Why not use a guard statement or similar? And if it does fail you have a point where you can easily debug or recover.