Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialShikhar Prateek
13,908 PointsHow to return the values
I am not able to figure out how to return values
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!")
}
}
// Enter your code below
class Robot: Machine {
override func move(direction: String) {
switch direction {
case "Up": return x += 1
case "Down": return y -= 1
case "Left": return x -= 1
case "Right": return x += 1
default: break
}
}
}
Shikhar Prateek
13,908 PointsThanks for replying.
2 Answers
Alexander Smith
10,476 PointsClose. No need to write return and you must reference the location inherited from the superclass machine like such...
class Robot: Machine {
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
}
}
}
also, this way if you were to use this if you entered up more then once it would go up as many times as you executed it instead of going to the coordinate point x:1 y:0 everytime. referring to the comment above
Shikhar Prateek
13,908 PointsThanks for replying. It works, but why aren't we using 'return'?
Alexander Smith
10,476 Pointswell in this case we aren't returning anything in this function, just manipulating the location variable referenced from the machine class. If we were writing this switch statement in a func that returned an Int or String for example then we would
Shikhar Prateek
13,908 PointsGot it. Thanks for replying.
Alexander Smith
10,476 PointsAnytime. Happy Coding!
David Welsh
9,298 PointsDavid Welsh
9,298 PointsJust a quick observation, you are trying to call on "x" in the switch/case, but x is only defined in the class "point". Try to add something like this, it might work: case "Up": Point(x: 1, y:0)
Here, I'm calling on the class Point to move the x value up.