Tristen
Tristen

Reputation: 382

Swift Subclass methods not being recognized

I'm working with SpriteKit and I have a subclass written for the SKSpriteNode class.

class PlayFieldNode: SKSpriteNode {

    var myFunction: (()->())?

    // other methods

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
        if let f = myFunction {
            f()
        }
    }

}

Inside a child node of the PlayFieldNode I want to do,

self.parent!.myFunction = self.myFunction

When I try to do this, it won't even compile and it gives warning like, Value of type 'SKNode' has no member 'myFunction'

I'm relatively new to working with swift, am I missing something involving inheritance or closures? I've double-checked and made sure that the parent is in fact the PlayFieldNode that I want to use.

Upvotes: 0

Views: 50

Answers (1)

Asperi
Asperi

Reputation: 258267

Yes, because parent is base SKNode class, which knows nothing about your myFunction, so you need at first to detect if parent is-a your subclass, so use

if let parent = self.parent as? PlayFieldNode {
   parent.myFunction = self.myFunction
}

Upvotes: 2

Related Questions