iOS Build a Simple iPhone App with Swift Getting Started with iOS Development Swift Recap Part 2

Leo Novel
Leo Novel
1,471 Points

Hello everyone! What am I doing wrong?

I don't seem to be able to get this code working! I appreciate an insights.

robots.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 am a machine!")
  }
}

// Enter your code below
class Robot: Machine {
     init(location: Point) {
        super.init()
        self.location = Point(x: 0, y: 0)

    }
    func move(_ direction: String) -> Point {
        switch direction {
        case "Up":
           location.y = location.y + 1
        case "Down":
            location.y = location.y - 1
        case "Right":
            location.x = location.x + 1
        case "Left":
           location.x = location.x - 1
        default:
            break
        }
       return location
    }

}

1 Answer

Ian Billings
PRO
Ian Billings
Pro Student 7,494 Points

Hi Leo,

There are a couple of issues. First of all there is no need for the initialiser for the Robot class. The challenge only requires you to implement the move method, and as its a subclass and no additional parameters are added it can use the parent class' init method. Secondly the move method in the robot class doesn't match the move method in the parent class, as the Robot's version is returning a Point object, when it shouldn't return anything. The method should also be overriding method.

override func (_ direction: String) {
//Method Body
}

Your method also doesn't need the return statement, as it should be a non returning (void) method. Hope that helps

Ian

Leo Novel
Leo Novel
1,471 Points

Indeed it helped. Thanks a lot! I hope I'll learn fast and will be a help to other novice programmers soon!! :)