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 trialPaul Je
4,435 PointsLooking for Explanation
Hey guys,
Just kind of confused and wanted to clarify. Does "switch" mean you're switching the constraint (direction) for the result of each case? If not, what's an easy description on how to understand what a switch is?
Secondly, what's the reasoning behind using location.y instead of Point.y for example?
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 direction {
case .Left: location.x -= 1
case .Right: location.x += 1
case .Up: location.y += 1
case .Down: location.y -= 1
}
}
3 Answers
jcorum
71,830 PointsPaul, just noticed you have a missing closing curly brace:
func move(direction: Direction) {
// Enter your code below
switch direction {
case .Left: location.x -= 1
case .Right: location.x += 1
case .Up: location.y += 1
case .Down: location.y -= 1
} //missing
}
The function takes one parameter, a direction. Think of switch as a shorthand way of writing if...else if...else... statements. Thinking this way, the first case says: if direction is Left, then do something. The second case says: else if direction is Right, then do something different.
In each case, what is done is either the x or y value of location (which is a Point) is incremented or decremented.
Damien Watson
27,419 PointsHi Paul,
A 'switch' statement checks a variable and then directs the flow to the relevant code. As in real life, when a train arrives at a switch based upon what train it is, it is then directed to the relevant track (I know nothing of trains so forgive my ignorance train lovers ;).
Another way to think of a switch (thought much messier) is using if statements, else if, else if etc.
Location is created as a variable of method Point, so using Point.y wouldn't make sense. When you set Location = Point(x:0, y:0), you are saying set Location to a Point object with x=0 and y=0.
Paul Je
4,435 PointsThanks guys makes so much more sense !
Damien Watson
27,419 PointsDamien Watson
27,419 PointsAs he said ;)