问:为什么这段代码是错误的?
它适用于 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
}
}
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
}
}
答:问题在于 Robot 类中的覆盖 init() 方法。只要摆脱这种方法,一切正常。(我想不知何故你误解了机器人应该用不同的原点初始化,但事实并非如此。因为这意味着在使用移动功能后它将具有与挑战预期不同的坐标,它不会不通过)