iosswiftuiviewsprite-kitskview

Thread 1 signal SIGABRT crash when casting UIView to SKView


I have the following code in GameViewController.swift:

override func viewDidLoad() {
    super.viewDidLoad()

    let scene: GameScene = GameScene()

    let currentView = self.view as! SKView
    currentView.showsFPS = true
    currentView.showsNodeCount = true

    currentView.presentScene(scene)
}

It crashes at let currentView = self.view as! SKView. with this message:

Could not cast value of type 'UIView' (0x1079b7e88) to 'SKView' (0x106b79718)

There was a similar question posed, but their solution was in the storyboard. I have no storyboards, just code.


Solution

  • You are getting a crash because your UIView's (i.e. your self.view) actual type is NOT an SKView. So you can't downcast to an SKView because it is not an SKView. So wherever you create your ViewController's view you must be assigning it a UIView. You said you are not using storyboards so I assume you are creating the ViewController programmatically. If this is the case, you need to manually assign your ViewController's view an SKView. This is typically done in the loadView method of the ViewController. You can see an example of this here