Ankonian
Ankonian

Reputation: 13

Swift - create array of class objects

I am trying to create an array that will store my class objects. The createEnemies method is called when a level is started. Which should then create the enemy objects. However I don't understand how to do that. It should be created after "if(levelNumber < 5)"

class level {
    class func createEnemies() {
        numEnemies = Int(floor(levelNumber * 1.5 + 10))
        println("Number of Enemies this level: \(numEnemies)")

        if(levelNumber < 5){
            //Create numEnemies amount of class objects

        }
    }
}

//Enemy Variables
var enemiesKilled = 0

class enemy {
    class func enemiesKilled() {

    }

    class standard {

        var health:Int = 10
        var name:String = "Standard"
        var worth:Int = 10
        var power:Int = 10

        init () {

        }

        func kill() {

        }

        func damage(damage: Int) {
            self.health -= damage
            println("\(self.name) was damaged \(damage)")
            if(self.health <= 0){
                self.kill()
            }

        }
    }

Upvotes: 1

Views: 5532

Answers (3)

ylgwhyh
ylgwhyh

Reputation: 1598

For Swift 3.1

var enemies:[enemy] = [enemy]()

Upvotes: 2

Qbyte
Qbyte

Reputation: 13243

If you want to have a specific number of enemies in the array there are several ways to achieve this (I write Enemy instead of enemy because the first letter of a class name is usually uppercase):

// "old fashioned" for loop
var enemies = [Enemy]()
for _ in 1...numEnemies {
    // call initializer of Enemy
    enemies.append(Enemy())
}

// my personal preference (Range has a method named map which does the same as Array)
// without the "_" you could also access the numbers if you want
let enemies = (1...numElements).map{ _ in Enemy() }

If you need to access the array later on you should declare the variable under your comment //Enemy Variables.

Upvotes: 1

trevorj
trevorj

Reputation: 2039

Create an array of elements of a custom class like this:

var enemies = [enemy]()

You can add elements to it like this:

enemies.append(anEnemy: enemy)

Upvotes: 1

Related Questions