2

Let's say I have 5 SKLabelNodes. Each is named incrementally. myLabel0,myLabel1 etc... They are all added to a SKScene. How do I set and get the label with a string. Something like:

for i in 0..5 {
 self["mylabel\(i)"].text = "Label \(i)"
}

I know that in other languages you can do things similar to this.

Johnston
  • 20,196
  • 18
  • 72
  • 121
  • possible duplicate of [Does Swift support reflection?](http://stackoverflow.com/questions/24060667/does-swift-support-reflection) – Sulthan Jun 26 '14 at 14:11
  • You can't. Use an array instead. There are languages that support reflection but it's never the preferred way to do things. – Sulthan Jun 26 '14 at 14:12
  • 1
    Explanation of the downvote? Does this question not show any research effort? Is it unclear? It is not useful? I've never heard of reflection. – Johnston Jun 26 '14 at 14:15
  • I do not see any downvotes (maybe someone downvoted and someone else upvoted or the downvoter changed his mind). There are two votes for closing as duplicate. I disagree with them because reflection is not the only way to do what you want to do. It would be in Swift, but there are languages that can do it with no need for actual reflection. – Analog File Jun 26 '14 at 16:44

1 Answers1

1

An SKScene is a subclass of SKNode and nodes form a tree through parent/child relationships. Rephrased, your question is 'how can I access a child of a SKNode using subscript notation with a string index'.

As such

extension SKNode {
  subscript (name: String) -> SKNode? {
    return self.childNodeWithName (name)
  }
}

If name is not a child of self, then perhaps you'd want to recurse on the children.

GoZoner
  • 67,920
  • 20
  • 95
  • 145