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 trial

iOS Enumerations and Optionals in Swift Introduction to Enumerations Enums and Objects

Michel Ortega
Michel Ortega
2,279 Points

I 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.

test.swift
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
Greg Kaleka
39,021 Points

Hi 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):

yourCode.swift
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:

  1. way does not exist - we should switch on direction, which is passed into this function. Note that this is completely unrelated to the enum Direction. They just happen to be the same word. Poor coding choice if you ask me...
  2. Your x's and y's are swapped
  3. the code location.y -1 is not valid - to add or subtract from an existing value, we should use the operators += and -=
solution.swift
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 :beers:

-Greg

Michel Ortega
Michel Ortega
2,279 Points

Thanks. It makes a lot of sense. Thank you.