继承符合协议的类

时间:2015-07-15 15:41:14

标签: swift

我无法弄清楚为什么Xcode游乐场会崩溃,这是我的基本设置

protocol Shootable {
    func shoot()
}

class BaseMissile: Shootable {

    var damage = 0

    func shoot() {
        println("Pew pew for \(damage) damage")
    }
}

class Missile1: BaseMissile {

    override init() {
        super.init()
        damage = 1
    }

}

protocol Targetable {
    var life: Int {get set}
}

class BaseSpaceship: Targetable {

    var life = 0
    var currentMissile: BaseMissile!

    func printHealth() {
        println("My current life: \(life)")
    }

}

class Spaceship1: BaseSpaceship {


    override init() {
        super.init()
        life = 1
        currentMissile = Missile1()
    }
}

var spaceship = Spaceship1()
spaceship.printHealth()
spaceship.currentMissile.shoot()

特别是最后一行spaceship.currentMissile.shot()使操场崩溃。如果我将var currentMissile: BaseMissile!BaseSpaceship移到Spaceship1,那么它是否有效,但这是否可以接受?

1 个答案:

答案 0 :(得分:0)

我想这是因为BaseSpaceship类没有初始化器而var currentMissile: BaseMissile!不能为零。所以你要么应该通过替换来做它是可选的!用?或者给它一个默认值。