Steve Ives Steve Ives - 5 months ago 28
Swift Question

removeAllChildren vs. issuing 'removeFromParent' for all nodes in self.children?

I'm following a SpriteKit tutorial, and for a sub-class of SKSpriteNode, they have the following code:

for child in children {

Why use this instead of:


? To me, removeAllChildren would be the obvious choice. I know that one is asking the parent to remove all its children, and the other is asking all the children to remove themselves from their parent, and I wondered if there was one subtlety I'm missing.

For further information, this was in the Ray Wenderlich tutorial 'CatNap' which is part of a paid-for series of tutorials. The code is in a function in a subclass of SKSpriteNode and is used to change the appearance of the node by removing all the children (eyes, tail, etc.) and replacing them with a new node. Here is the function:

func wakeUp() {
for child in children {
texture = nil
color = SKColor.clearColor()

let catAwake = SKSpriteNode(fileNamed: "CatWakeUp")!.childNodeWithName("cat_awake")!

catAwake.position = CGPoint(x: -30, y: 100)

I did wonder if
wasn't available when the tutorial was written, but
was introduced with SpriteKit in iOS 7, so that doesn't appear to be it.


I have replaced the child.removeFromParent loop with a single removeAllChildren with no apparent change in behaviour. I suspect that the author of the tutorial just didn't know that this function was available.

It's possible that if you subclass SKNode and override removeFromParent, you could introduce some custom behavior that removeAllChildren wouldn't action.