skip to Main Content

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


  1. 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
      }
    }
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search