OGeek|极客世界-中国程序员成长平台

标题: ios - Swift 4 - 无法在没有参数的情况下调用 'Spaceship.init' [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:18
标题: ios - Swift 4 - 无法在没有参数的情况下调用 'Spaceship.init'

这是我的代码。我已经坚持了一段时间。我似乎无法弄清楚。我正在遵循的指南希望我在 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.")
        }
    }
}



Best Answer-推荐答案


您没有将类中的所有实例变量设置为传递值的初始化程序。除非有特定的有效默认值,否则每个值都有一个单独的 init 是很奇怪的。我建议您阅读 designated initializers并且可能会修改您的代码以在 Spaceship 中有一个 init(name:health:position 初始化程序和一个 init(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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4