Animator Joe
Animator Joe

Reputation: 69

Pass Array By Reference [Swift 3 Xcode 8]

I have created a bullet class, and I want it to hold an attribute called locatedInArray. locatedInArray stores a reference of the array that the bullet is stored in within the GameScene class. The only problem is that when I add print statements, it shows that the locatedInArray has different values when compared to the actual array in the game scene. Is there anyway to pass the array by reference instead of value?

The array being passed through a function call to the bullet instance.

bullet.shoot(from: self.mainCharacter, to: "right", fromPercentOfWidth: 0.5, fromPercentOfHeight: 0.65, addToArray: &playerBulletArray, inScene: self)

Array being assigned as attribute inside bullet object.

func shoot(from character: SKSpriteNode, to direction: String, fromPercentOfWidth xPercent: CGFloat, fromPercentOfHeight yPercent: CGFloat, addToArray array: inout[SKBulletsNode?], inScene scene: GameScene) {

    self.gameScene = scene
    self.locatedInArray = array
}

Upvotes: 0

Views: 790

Answers (1)

Dustin Spengler
Dustin Spengler

Reputation: 7711

Could you create a class which contains the SKBulletsNode array as a property and pass a single one of those objects into the function?

like this:

class BulletArray {
    var bullets : [SKBulletsNode]?
}

func shoot(from character: SKSpriteNode, to direction: String, fromPercentOfWidth xPercent: CGFloat, fromPercentOfHeight yPercent: CGFloat, addToArray array: inout BulletArray , inScene scene: GameScene) {
   self.gameScene = scene
   self.locatedInArray = array
}

check out this link for more info: Swift: Pass array by reference?

Upvotes: 1

Related Questions