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 trialLing Cheng
3,168 PointsCan't this be work too?
What's the problem with this one? Thanks!
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) {
if direction == "UP" {
location.y + 1
}
else if direction == "DOWN" {
location.y - 1
}
else if direction == "LEFT" {
location.x + 1
}
else if direction == "RIGHT" {
location.x - 1
}
}
}
2 Answers
Steve Hunter
57,712 PointsHi there,
A few points on this.
FIrst, you might want to consider using a switch
statement to handle the multiple options, rather than chaining a load of if
statements together. There's a post about that here.
Secondly, you aren't changing the value of the location
components. Saying location.y + 1
doesn't increment location.y
you either need to assign that back into location.y
or use the unary increment operator, ++
:
// assign the value to change it
location.y = location.y + 1
// or increment
location.y++
You don't need to assign the result of the ++
operator - it works just fine like that.
Thirdly, I think the strings being input are capitalised initials, rather than ALL CAPS, so you may want to try testing for "Up
" rather than "UP
".
I hope that helps - let me kow how you get on.
Steve.
Ling Cheng
3,168 PointsThanks very much, I understand now.
Steve Hunter
57,712 PointsNo problem!