Search code examples
iosarraysswiftmutable

How to create a mutable array of specific class type in Swift


I have a class called Bullet and I want to make a mutable array with this class type. Basically the desired outcome I want is, when a user touches the screen a new bullet is spawned. I know in Java you can use an ArrayList to achieve this by adding a new instance to the array list each time.

I'm not sure syntactically how I could achieve in Swift or if it is even possible. This is the code I have for declaring and instance of the Bullet class but how do I make it so that it is a mutable array...

var bullet: Bullet = Bullet()

Thank you!


Solution

  • Its simple :

    var bulletArray = [Bullet]() // this will declare and initialize the bulletArray
    

    In the above line of code the type is inferred for the bulletArray.

    If you explicitly want to specify the type then,

    var bulletArray:[Bullet] = [Bullet]() // this will declare and initialize the bulletArray
    

    If you just want to declare the array but not initialize then

    var bulletArray:[Bullet]
    

    If you just declare the array then you need to initialize it in init() before using it. Or else you can declare array as optional type. As shown below,

    var bulletArray: [Bullet]?
    

    HTH :)