Starting with swift 4.2, an error appears. In previous versions the code works fine (swift 3, 4). How to write this code correctly now?
swift4
swift4.2
class GameViewController: UIViewController {
var scene: SCNScene!
var scnView: SCNView!
override func viewDidLoad() {
super.viewDidLoad()
setupScene()
setupView()
}
func setupScene() {
scene = SCNScene()
}
func setupView() {
scnView = self.view as! SCNView
scnView.scene = scene
}
}
2
Answers
Instead of force downcasting, use optional downcasting.
If
self.view
can’t be downcasted asSCNView
it’ll returnnil
You can also handle failure like this:
This seems like an instance of this bug, caused by the thing you are assigning to,
scnView
, being an (implicitly unwrapped) optional, and you are usingas!
. It seems to be suggesting that since you are assigning to an optional, you could just useas?
which produces an optional instead, and doesn’t crash.Assuming that you are sure that
self.view
is anSCNView
(because you have set it in the storyboard, for example), and you want it to fail-fast when it is somehow notSCNView
, you can silence the warning by adding brackets: