Search code examples
iosswiftsprite-kitsknode

Cannot cast SKNode to subclass of SKNode


I am returning an SKNode from one function and I need to cast it to a custom SKNode. I get the error Cannot assign value ofSKNodeto typeGroundNode. If I force cast, it compiles, but fails at runtime. What am I missing?

// Custom node class
class GroundNode: SKNode {
        weak var entity: GKEntity!
    }

// Return node function
func returnNode() -> SKNode {
    ...
    return node
}

// Where I am getting the error
func setupNode() {
    var ground: GroundNode
    ground = returnNode() // error here.
    //// ground = returnNode() as! GroundNode fails at runtime.
}

EDIT: I am getting an SKNode from an sks file. My returnNode() just get the child with name, and returns it to my setupNode() function. I need to add the entity property, so I want to cast my returned SKNode to a GroundNode type.

I have seen this stackoverflow post.

This works with SKSpiteNode, but apparently not with SKNode, which does not make much sense to me.

If I cast my SKNode from my sks file to a GroundNode, it crashes at runtime.


Solution

  • Based on your code:

    // Custom node class
    class GroundNode: SKNode {
        weak var entity: GKEntity! = GKEntity() // or some custom initialization...
    }
    
    // Where I am getting the error
    func setupNode() {
       var ground: GroundNode
       ground = returnNode() as? GroundNode
    }
    

    This happened because returnNode output is a generic SKNode and you must explicit your casting to the subclassed GroundNode.

    EDIT: Ok, with your update I think I've understand your issue, you've forgot to set the custom class for your GroundNode:

    enter image description here