Drakalex
Drakalex

Reputation: 1538

Enumerate class members in Swift

I'm working with Swift and SpriteKit

I have a class :

class Button: SKShapeNode
{
}

And I have some buttons:

var button1 = Button()
var button2 = Button()

And I already use the ".name" of those nodes :

button1.name = "button1"
button2.name = "button2"

So normally, I enumerate thoses nodes with enumerateChildNodesWithName("button") but here, the name is already taken, so how could I enumerate all of my buttons (that use the class Button) ?

Upvotes: 1

Views: 82

Answers (2)

danielbeard
danielbeard

Reputation: 9149

You can use the children property of the node:

var buttonNodes = node.children.filter { $0 is Button }

Complete example:

import UIKit
import SpriteKit

let node = SKNode()

class Button: SKNode {
}

let button1 = Button()
let button2 = Button()
let label = SKLabelNode()

node.addChild(button1)
node.addChild(button2)
node.addChild(label)

let buttons = node.children.filter { $0 is Button }
print(buttons.count) // buttons only has 2 elements, the button nodes!

Upvotes: 1

nathangitter
nathangitter

Reputation: 9777

You can enumerate all the child nodes of a given node by calling enumerateChildNodesWithName with //* as the node name. This is listed as an example in Apple's documentation here.

Then in the block check to see if the node is of type Button and perform your action accordingly.

So something like this:

myNode.enumerateChildNodesWithName("//*") { node, ptr in
    if node is Button {
        // do something here
    }
}

Upvotes: 1

Related Questions