Rookie Question about SpriteKit Wizard in Swift

Hi,


I've a very simple Swift question which answer must be straightforward but I can't figure it.


In Xcode 8.2, the SpriteKit wizard sample in Swift creates a GameViewController viewController whose view is of type SKView.


The viewDidLoad method is:


override func viewDidLoad() {
     super.viewDidLoad()
     if let view = self.view as! SKView? {
          [...]
          view.showsFPS = true
     }
}


My question is about the optional bindind. I find hard to expain why the optional binding is simply not :


     if let view = self.view as? SKView {
          [...]


It seems simplier to me.


Maybe the wizard version shows that the coder is sure that the view is of type SKView. In this case, why not simply :


override func viewDidLoad() {
     super.viewDidLoad()
     let view = self.view as! SKView
     view.showsFPS = true


Thank you for any response, and sorry for this simple question!


Jice

Answered by QuinceyMorris in 205180022

I don't know the answer for sure, but the code as originally written is slightly more subtle than your re-writes. There are 3 possible cases:


1. a SKView

2. a NSView that is not a SKView

3. nil


The original code will crash deliberately on case 2 (which is a mis-configured storyboard, in effect), and branch on the difference between 1 and 3. Your 1st rewrite branches on 2 and 3, and your second rewrite crashes on 2 and 3.


In any actual use case, where you have direct control over the storyboard, you can probably customize the code to require a top-level SKView (or subclass), in which case your second rewrite may well be sufficient, and less confusing to future readers of the code.

Accepted Answer

I don't know the answer for sure, but the code as originally written is slightly more subtle than your re-writes. There are 3 possible cases:


1. a SKView

2. a NSView that is not a SKView

3. nil


The original code will crash deliberately on case 2 (which is a mis-configured storyboard, in effect), and branch on the difference between 1 and 3. Your 1st rewrite branches on 2 and 3, and your second rewrite crashes on 2 and 3.


In any actual use case, where you have direct control over the storyboard, you can probably customize the code to require a top-level SKView (or subclass), in which case your second rewrite may well be sufficient, and less confusing to future readers of the code.

As the code and the storyboard was produced by Xcode SpriteKit wizard, I was confused by this implementation choice.


Now, it's clear, thank you very much for your clear answer.

Rookie Question about SpriteKit Wizard in Swift
 
 
Q