0

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
}

}

dmitrique
  • 1
  • 1

2 Answers2

0

Instead of force downcasting, use optional downcasting. If self.view can't be downcasted as SCNView it'll return nil

func setupView() {
  scnView = self.view as? SCNView
  scnView.scene = scene
}

You can also handle failure like this:

func setupView() {
  if let scnView = self.view as? SCNView {
    scnView.scene = scene
  }
  else {
    // self.view couldn't be cast as SCNView, handle failure
  }
}
saurabh
  • 6,687
  • 7
  • 42
  • 63
0

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 using as!. It seems to be suggesting that since you are assigning to an optional, you could just use as? which produces an optional instead, and doesn't crash.

Assuming that you are sure that self.view is an SCNView (because you have set it in the storyboard, for example), and you want it to fail-fast when it is somehow not SCNView, you can silence the warning by adding brackets:

scnView = (self.view as! SCNView)
Sweeper
  • 213,210
  • 22
  • 193
  • 313