Confused Confused - 16 days ago 5
Swift Question

SpriteKit addChild(node: SKNode) plural?

Is there a plural version of this command, so I can type in a list of children to add?

Kind of like:

addChildren(myNodeABC, myNodeXYZ, myNode123)

Answer

Write an extension to do it: (I wrote it in Swift 3 style, I do not have XCode available right now to verify this works)

extension SKNode
{
    func add(children: SKNode...)  {
        for child in children{
            addChild(child)
        }
    }
}

usage:

node.add(children:node1,node2,node3)

note: ... is called variadic parameters in case you want to know more about them: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

If you want to use less lines, do:

extension SKNode
{
    func add(children: SKNode...)  {
        children.forEach({addChild($0)});
    }
}