Search code examples
swiftsprite-kitparent

Calling a parent's function in Swift


In Swift, I am trying to call a function on a node's parent, like this:

self.parent.unhighlightAllCheckers()

Didn't work. I think this is because the child node may not implicitly know what type of object the parent is, so I try an explicit cast:

let myParent: Gameboard = Gameboard(self.parent)
myParent.unhighlightAllCheckers()

Also doesn't work. I am thinking this should be far simpler. How do you call a parent node's function?


Solution

  • if let myParent = self.parent as? Gameboard {
        myParent.unhighlightAllCheckers()
    }
    

    The explicit cast you have doesn't make sense as you're not using it in the next line.

    You're not casting you're actually creating a new Gameboard by calling the constructor. Casting would be using the as operator.

    More importantly, when you do copy/cast/whatever be sure to use the variable you just created.

    The if let ... as? idiom in Swift is pretty great and there are more examples in the manual. https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html