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 = trueThank you for any response, and sorry for this simple question!
Jice
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.