Swift - 创建类对象数组

时间:2015-07-08 18:11:50

标签: arrays swift class loops object

我正在尝试创建一个存储我的类对象的数组。启动级别时会调用createEnemies方法。然后应该创建敌人对象。但是,我不明白该怎么做。它应该在" 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()
            }

        }
    }

3 个答案:

答案 0 :(得分:1)

创建一个自定义类的元素数组,如下所示:

\jj

您可以像这样添加元素:

var enemies = [enemy]()

答案 1 :(得分:1)

对于Swift 3.1

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

答案 2 :(得分:0)

如果你想在数组中有特定数量的敌人,有几种方法可以实现这一点(我写Enemy而不是enemy,因为类名的第一个字母通常是大写的) :

// "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() }

如果您稍后需要访问该数组,则应在评论//Enemy Variables下声明该变量。