Reputation: 367
I want to create a pool of sprites that I can move around on the screen without having to reinitialize and add them to my scene over and over.
To do this, I want to store a collection of objects in a way that I can easily access and mutate the objects.
My initial thought was to use an Array, but it appears Swift passes back a copy of an object when I reference the array.
var nodes:[SKNodes] = SKNodes();
nodes.append(SKNode());
nodes[0].position = CGPoint(x: 100, y: 100) //doesn't work
What is the best practice for creating something like this?
EDIT:
It wasn't working due to a typo, silly me. For some reason I thought it wasn't working because Swift would pass by value, and I would get a copy of the object in the array instead of a reference to the object.
I have now learned that Swift passes Objects and Functions as a Reference Type, and basically only structs and enums are pass by value
Is Swift Pass By Value or Pass By Reference
var nodes:[SKNode] = SKNodes();
nodes.append(SKNode());
nodes[0].position = CGPoint(x: 100, y: 100) //Works!
Upvotes: 2
Views: 248
Reputation: 7013
Since you append SKNode
to the Array
, it should be [SKNode]
instead of [SKNodes]
var nodes:[SKNode] = SKNodes();
nodes.append(SKNode());
nodes[0].position = CGPoint(x: 100, y: 100) //should work
Upvotes: 2