I am trying to allocate sprite data to a global array using preset indexes for the sprites. I am initializing the array as an array of SKSpriteNodes. I am sending SKSpriteNodes to this array, each sprite has a set index for this array. I realize I could also do this with a loop instead of setting indexes, but I want to figure out the array allocation first.
I have tried reserveCapacity(27) because there will be 27 sprites to pass in, but when I try I get an index out of range error.
class GameScene: SKScene
{
//main array that will be used to store sprite button data
var mainArr: [SKSpriteNode] = [SKSpriteNode]()
..
override func didMove(to view: SKView)
{
mainArr.reserveCapacity(27)
...
if let name = touchedNode.name
{
if name == "pea"
{
peaFlag = peaFlag * -1
manageArrayData(name: pea, nameFlag: peaFlag, nameIndex: peaInd)/*may need to add images*/
}
...}//end touchNode
...} //end didMoveTo
func manageArrayData(name: SKSpriteNode, nameFlag: Int, nameIndex: Int)
{
if nameFlag >= 0
{
print(nameFlag)
print(nameIndex)
print("in array")
mainArr.insert(name, at: nameIndex)
//dump(mainArr)
print("-=-=-=-in-=-=-=-")
}
as I said, the error is: Fatal error: Array index is out of range 2019-06-27 09:54:09.414271-0700 Select[36307:1432579] Fatal error: Array index is out of range
I believe the error is because reserveCapacity() is of type Int, while I am trying to allocate memory for SKSpriteNode... therefore there is no space for what I am allocating, hence the "out of range"
there are multiple "buttons" (using SKSpriteNodes), so I created an if tree for the buttons to fall under.
reserveCapacity
does not create entries in the array. It just makes sure you won't need to perform a reallocation (and possible relocation) if you add that many entries. It's generally only needed for performance reasons. It won't change anything about how indexing works.
If you want empty entries in the array, you need to add them. See Array(repeating:count:)
to create an array with some fixed values.