0

Apple's boilerplate code for UISceneDelegate contains a stub implementation for scene(_:willConnectTo:options:). This starts with:

guard let _ = (scene as? UIWindowScene) else { return }

Is is really possible that we end up in the else branch here? The constructor of UIScene mentions

Subclasses call this method to initialize the scene details.

so my guess is that UIScene should be treated as an abstract base class that is never created directly, only from derived classes. But I didn't find any other classes derived from UIScene. If that holds true, wouldn't it make much more sense to write a forced downcast here?

scene as! UIWindowScene

Or is there a use case where it makes sense to create a user-defined subclass? If so, what would be an example for that and how would it be used?

Tobi
  • 2,591
  • 15
  • 34
  • Apple's sample code is much safer and more future-proof than simply assuming `scene` will always be a `UIWindowScene`. Maybe now all scenes are window scenes but maybe that could change in a future update to iOS. – HangarRash Mar 27 '23 at 17:45
  • @HangarRash I'd question that. If such a fundamental change came about, it's *highly* unlikely that just returning from the callback is the right thing to do. If we are lucky it leads to a crash somewhere else. Otherwise it can create a bug that might be hard to find. I'd always prefer an assertion failure (which the forced downcast would be) so I can easily find the spots I have to think about when editing the code for the iOS update in question. – Tobi Mar 27 '23 at 19:10

1 Answers1

1
  1. Are there UIScenes that are not UIWindowScenes? Yes.
    CarPlay framework has its own UIScene, UISceneDelegate.
  • UIScene : CPTemplateApplicationDashboardScene, CPTemplateApplicationScene, CPTemplateApplicationInstrumentClusterScene
  • UISceneDelegate : CPTemplateApplicationSceneDelegate, CPTemplateApplicationDashboardSceneDelegate, CPTemplateApplicationInstrumentClusterSceneDelegate
  1. Is force casting is safe? Force casting is safe unless you share SceneDelegate with different Role.
    UIKit expects to have concrete subclass of UIScene for each Role. For example, windowExternalDisplayNonInteractive, windowApplication, windowExternalDisplay should connect to UIWindowScene.

  2. Is there a use case where it makes sense to create a user-defined subclass?
    Rarely there could be, but using different UISceneDelegate for different Role is more preferred way.

Watermelon
  • 452
  • 2
  • 5