我是新来的迅速。我正在迅速进行App开发中的练习。类的成员初始化器和引用。

我不知道如何解决这个问题。问题是编写自己的初始化程序,而不提供所有内容的默认值。

class Spaceship {
    let name: String
    var health: Int = 100
    var position: Int = 0

    func moveLeft() {
        position -= 1
    }

    func moveRight() {
        position += 1
    }

    func wasHit() {
        health -= 5
    }

    init(name:String, health:Int, position:Int) {
        self.name = name
        self.health = health
        self.position = position
    }
}

class Fighter: Spaceship {
    let weapon: String
    var remainingFirePower: Int

    init(weapon:String,remainingFirePower:Int) {
        self.weapon = weapon
        self.remainingFirePower = remainingFirePower
        super.init(name: name, health: health, position: position)
    }

    func fire() {
        if remainingFirePower > 0 {
            remainingFirePower -= 1
        } else {
            print("You have no more fire power.")
        }
    }
}

class ShieldedShip: Fighter {
    var shieldStrength: Int

    override func wasHit() {
        if shieldStrength > 0 {
            shieldStrength -= 5
        } else {
            super.wasHit()
        }
    }
    init(shieldStrength:Int, weapon:String, remainingFirePower:Int){
        self.shieldStrength = shieldStrength
        super.init(weapon:weapon, remainingFirePower:remainingFirePower)
    }
}

最佳答案

了解有关optional类型的信息。你可以写:

let name: String?
var health: Int?
var position: Int?


Link for optional types

关于swift - 错误:在属性中使用“自我”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44778603/

10-13 03:59