Sprite Kit view setup crash (Swift)

84 views Asked by At

I have an UIView that i want to add a SKScene to. In the step were i declare "skView" it crashes.

var skView=view as SKView; 
var skScene=gameScene();
skView.presentScene(skScene)
1

There are 1 answers

0
rickster On

The as operator doesn't work that way. In order to treat a value of one type as another type, two things need to be true:

  • the second type needs to be more specific than the first
  • the value needs to actually be of the second type.

You've got the first, but not the second. For example, if I give you something and all I say is that it's a Car, you're welcome to accelerate() it all you want (don't forget to brake() too), but if you want to engageClutch() you'll need to treat it as a StickshiftCar. I may or may not have given you a StickshiftCar, though—if what you actually have is something else, you can't just say "treat this like a stickshift" to make it one.

If you want to use an SKView, you'll first need to get yourself one. If your view is set up in a storyboard, use IB to make the view controller's root view an SKView. Then, in code, you can access self.view (which is just a UIView for all that property knows) and safely treat it as an SKView.