gpt4 book ai didi

ios - Swift 4 - 无法在没有参数的情况下调用 'Spaceship.init'

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:09:02 25 4
gpt4 key购买 nike

这是我的代码。我已经坚持了一段时间。我就是想不通。我遵循的指南要我在 Fighter 子类中使用 super.init(),但每次尝试时似乎都会给我一个错误。

class Spaceship {
var name = String()
var health = Int()
var position = Int()
init(name: String) {
self.name = name
}
init(health: Int) {
self.health = health
}
init(position: Int) {
self.position = position
}
func moveLeft() {
position -= 1
}
func moveRight() {
position += 1
}
func wasHit() {
health -= 5
}
}

class Fighter: Spaceship {
let weapon: String
var remainingFirePower: Int
init(remainingFirePower: Int) {
self.remainingFirePower = remainingFirePower
}
init(weapon: String) {
self.weapon = weapon
super.init() //Cannot invoke 'Spaceship.init' with no arguments
}
func fire() {
if remainingFirePower > 0 {
remainingFirePower -= 1
} else {
print("You have no more fire power.")
}
}
}

最佳答案

您没有将类中所有实例变量设置为传递值的初始化程序。除非有特定的有效默认值,否则为每个值设置一个单独的 init 是很奇怪的。我建议你阅读 designated initializers并可能修改您的代码以在 Spaceshipinit(name:health:position:weapon:remainingFirePower :) Fighter 中的初始化程序调用 super 的实现并传递值。

如果有任何您不希望为空字符串或零的值,则不应为它们提供默认值,因此在初始化程序中需要它们。

这等同于将您的代码修改为具有指定的初始化程序,该初始化程序设置所有内容并具有默认值。

class Spaceship {
var name : String
var health : Int
var position : Int
init(name: String = "", health: Int = 0, position: Int = 0) {
self.name = name
self.health = health
self.position = position
}
func moveLeft() {
position -= 1
}
func moveRight() {
position += 1
}
func wasHit() {
health -= 5
}
}

class Fighter: Spaceship {
let weapon: String
var remainingFirePower: Int
init(name: String = "", health: Int = 0, position: Int = 0, weapon: String = "", remainingFirePower: Int = 0) {
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.")
}
}
}

关于ios - Swift 4 - 无法在没有参数的情况下调用 'Spaceship.init',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45179936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com