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 Swift 2.0 Enumerations and Optionals Introduction to Enumerations Enums and Objects

Enumerations & Optionals

Wonder why this doesn't work?

classes.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
        let Direction.Up = y+1
        let Direction.Down = y-1
        let Direction.Right = x+1
        let Direction.Left = x-1
    }
}

1 Answer

Matt, here's what you want the function to look like:

    func move(direction: Direction) {
        // Enter your code below
        if direction == .Up {
          location.y++
        } else if direction == .Down {
          location.y--
        } else if direction == .Right {
          location.x++
        } else {
          location.x--
        }
    }

First, there's no need to create constants inside the function. So no let keywords.

Second, the shorthand way to write x = x + 1 is x++, not x+1

Third, you only want the robot direction to change in one way, not four ways, when the method is called. So you will need a switch statement or an if...else if...else... statement. I show you the latter in the above code.

Fourth, direction is an Direction object, so it's going to have one of four values: .Up, .Down, .Right or .Left. You will test to see which in each path of the switch or if/else.

Hope this helps.