0

I have the following boiler plate code generated by Xcode when creating a SpriteKit + GameplayKit project:

override func viewDidLoad() {
    super.viewDidLoad()

    // Load 'GameScene.sks' as a GKScene. This provides gameplay related content
    // including entities and graphs.
    if let scene = GKScene(fileNamed: "GameScene") {

        // Get the SKScene from the loaded GKScene
        if let sceneNode = scene.rootNode as! GameScene? {

            // Copy gameplay related content over to the scene

            // Set the scale mode to scale to fit the window
            sceneNode.scaleMode = .aspectFill

            // Present the scene
            if let view = self.view as! SKView? {
                view.presentScene(sceneNode)

                view.ignoresSiblingOrder = true

                view.showsFPS = true
                view.showsNodeCount = true
            }
        }
    }
}

For testing different scenes, I would prefer to move all code after super.viewDidLoad() into a function, so that I can easily test different scenes without having to edit a lot of code.

The line that I'm getting stuck on is:

if let sceneNode = scene.rootNode as! GameScene? 

I am not sure how I can pass the class type in a generic manner to a function, so instead of GameScene? , I can pass the correct scene type.

How do I do this ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190

1 Answers1

1

You can use some more generic like the actual boilerplate code:

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        if let scene = SKScene(fileNamed: "GameScene") {
            scene.scaleMode = .aspectFill
            view.presentScene(scene)
        }
        view.ignoresSiblingOrder = true
        view.showsFPS = true
        view.showsNodeCount = true
    }
}

If all of your scenes inherit from SKScene, you will not have trouble.

But if you really need pass Type class on function to load, you can make something like this:

func loadScene<T>(named name: String, classType: T.Type) -> T? {
    return SKScene(fileNamed: name) as? T
}

And use:

let newScene = loadScene(named: "some", classType: GameScene.self)
// newScene is Optional(GameScene) type.

Sure you can remove optional replacing T? and control the nil of load.

Maetschl
  • 1,330
  • 14
  • 23
  • The problem is that GKScenes can only be loaded from files, and the class type has to be mentioned in the file... I worked around it by not using GKScene at all, but I’m still interested in my original question for purely academic reasons - how to pass a class type as parameter to a function in swift.... – Rahul Iyer Apr 19 '20 at 15:38