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 trialMichel Ortega
2,279 PointsI find myself confused about how to change the value of the. x & y coordinates. How do I solve the issue?
I just don't know how to set the value correctly.
class Point {
var x: Int
var y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
enum Direction {
case left
case right
case up
case down
}
class Robot {
var location: Point
init() {
self.location = Point(x: 0, y: 0)
}
func move(_ direction: Direction) {
// Enter your code below
switch way {
case Direction.left: location.y -1
case Direction.right: location.y +1
case Direction.up: location.x +1
case Direction.down: location.x -1
}
}
}
1 Answer
Greg Kaleka
39,021 PointsHi Michael,
You're close. When you write the code within a case of a switch statement, it needs to be just like any other swift code. Let's look at what you have (note I reformatted a bit - I find it much easier to read switch statements this way):
switch way {
case Direction.left:
location.y -1
case Direction.right:
location.y +1
case Direction.up:
location.x +1
case Direction.down:
location.x -1
}
Things we need to fix:
-
way
does not exist - we should switch ondirection
, which is passed into this function. Note that this is completely unrelated to the enumDirection
. They just happen to be the same word. Poor coding choice if you ask me... - Your x's and y's are swapped
- the code
location.y -1
is not valid - to add or subtract from an existing value, we should use the operators+=
and-=
switch direction {
case Direction.left:
location.x -= 1
case Direction.right:
location.x += 1
case Direction.up:
location.y += 1
case Direction.down:
location.y -= 1
}
Hope that makes sense!
Cheers
-Greg
Michel Ortega
2,279 PointsMichel Ortega
2,279 PointsThanks. It makes a lot of sense. Thank you.