问:为什么这段代码不能编译?
它在 Xcode 中完美运行
class Point { var x: Int var y: Int
init(x: Int, y: Int){
self.x = x
self.y = y
}
}
class Machine { var location: Point
init() {
self.location = Point(x: 0, y: 0)
}
func move(direction: String) {
print("什么都不做!我是机器!")
}
}
类机器人:机器{
override init(){
super.init()
self.location = Point(x: 1, y: 1)
}
override func move(direction: String) {
switch direction {
case "Up": location.y += 1
case " Down": location.y -= 1
case "Left": location.x -= 1
case "Right": location.x += 1
default: break
}
}
答:我认为问题是,您在子类初始值设定项之前使用了 super.init - 尝试切换它们。super.init 应该始终是子类初始值设定项中的最后一件事。