Can 'downcasting' to AppDelegate ever fail?

Viewed 844

When working with CoreData, we need access to the shared store which is available via the AppDelegate. To obtain a reference to the AppDelegate we can get it by doing the following:

guard let appDelegate = UIApplication.shared.delegate as? AppDelegate 
else {
        return
    }

Why do we have to be so safe when downcasting to the Appdelegate? Can the downcast ever fail for some reason and if so, why?

I have looked around and can't find a reason as to why we write this code, and wanting to know why I write things will help!

3 Answers

I can't agree with the point that force unwrapping downcasting to AppDelegate will never fail. It's isn't true. Because 'AppDelegate' could be the wrong type for your delegate. For example, I faced it when app used RxAppState framework. It has an extension for AppDelegate which returns 'RxAppState.RxApplicationDelegateProxy' class as the delegate. So always be careful.

Related