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 Build a Simple iPhone App with Swift 2.0 Getting Started with iOS Development Swift Recap Part 2

Haitham Alam
Haitham Alam
2,685 Points

Can i get an explained answer?

I am trying to build this code since yesterday but I am totally confused, can I get the correct answer please??

classes.swift
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

1 Answer

Tobias Helmrich
Tobias Helmrich
31,603 Points

Hey there,

if you would post your code it would be easier to find the eventual mistakes you made. About the solution: Basically all you have to do is to create a Subclass of Machine called Robot . Robot inherits from Machine as it is its subclass so now you can override the function move of the Machine class to fit the Robot class. To override the function you can simply put the override keyword in front of the func keyword.

In this case the robot should be able to move so for that you can add a switch statement with four possible cases ("Up", "Left", "Down", "Right") that determine the direction the robot should move. As a default value you should set the keyword break to exit the current iteration if the value of direction is none of the cases. For that you can modify the stored property location (which has the type Point) that Robot inherited from Machine and via dot-notation you can access its x and y values and modify them.

Like so:

// Enter your code below

// Create the subclass
class Robot: Machine {
  // Override the move function
  override func move(direction: String) {
    // Switch statement
    switch direction {
    case "Up": location.y += 1
    case "Down": location.y -= 1
    case "Left": location.x -= 1
    case "Right": location.x += 1
    default: break
    }
  }
}

Try to understand the solution and compare it to your version to see possible mistakes you made. I hope that helps, if you have further questions feel free to ask. Good luck! :)