类继承,重写方法和从超类访问存储的属性

时间:2015-12-14 15:59:11

标签: ios swift oop

我正在学习Swift和面向对象的编程,而且我一直被困在"测验"过去一周。我的任务是创建一个名为Robot的Machine的子类,然后从超类中覆盖move方法,这样当我输入一个特定的字符串时,机器人会移动(向上 - y ++,向下 - y--,向右 - x ++,向左 - y - )

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("Do nothing! I'm a machine!")
    }
}

我真正在努力学习如何超越移动方法。这是我的思考过程 - 请纠正我错在哪里:

//The Robot class inherited the location stored property from its superclass; this property includes x and y as its of type Point
//x and y are already initialized in Robot because they're initialized in its super class
//I need to OVERRIDE the move method, so I cannot add x and y to the method's parameters or add a return type
//Therefore, I need to affect x and y without passing them into the method as arguments... and this is where I'm lost

这是我认为需要发生的一般概念:

class Robot: Machine {
    let isRobot: Bool = true

    override func move(direction: String) {
        switch direction {
            case "Up":
            y++
            case "Down":
            y--
            case "Right":
            x++
            case "Left":
            x--
        default:
            break
        }
    }
}

如果它甚至可能影响方法中的x和y而不将它们作为参数传递,我尝试了self.location = Point(x:x + 1,y)和self.location + = Point.x没有成功。这些是我的新概念,非常感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

你非常非常接近。您唯一的错误是xy不是Machine的属性。他们是Machine.location的属性。

您的self.location = Point(x: x+1, y)应该有效,所以我很好奇"没有成功"意思是那里。更简单的方法与您完成的方式完全相同,但修改位置:

     case "Up":
         location.y++

可能不相关,但您的Point明显更好地实施为struct而不是class。使用Point作为可变引用类型(包含var属性的类)可能会导致很多混淆。如果两个Robot实例传递相同的Point,那么对一个实例的修改也将修改另一个实例,这将是非常令人惊讶的。另一方面,struct是值类型。如果你将它传递给某个东西,那么接收者就会得到它自己的副本。

当事物具有身份及其自身状态时,最好使用引用类型(类)。位于同一位置的两个机器人仍然是不同的机器人。但是在同一位置的两个点是相同的点。这意味着积分是值,应该是struct

相关问题