我是swift的新手。我正在快速进行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)
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
此处为您想要的内容
init(name:String = "ship", health:Int = 100, position:Int = 0) {
self.name = name
self.health = health
self.position = position
}
基本上,你想要像这样设置默认值,如果你只想用默认值初始化它,将NOTHING传递给这个函数,就像这样
super.init()