我无法弄清楚为什么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
,那么它是否有效,但这是否可以接受?
答案 0 :(得分:0)
我想这是因为BaseSpaceship
类没有初始化器而var currentMissile: BaseMissile!
不能为零。所以你要么应该通过替换来做它是可选的!用?或者给它一个默认值。