Bummer! You must be logged in to access this page.

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: Changing value of int not reflected in method call

In code challenge "Swift Recap Part 2" we're tasked to subclass Machine and its method. I did so successfully, which is great.

To challenge myself further, in a Playground I added a method robotLocation to the super class. I wanted check where the Robot instance's location was after calling the move method a few times.

I can call the method, of course, but it doesn't reflect the changes made after calling move.

Why is this?

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! Im a machine!")
    }

    func robotLocation() -> String { // New method
        return("\(location.x) by \(location.y)")
    }
}

class Robot: Machine {
    override init() {
        super.init()
    }

override func move(direction: String) {
    switch direction {
        case "Up": location.y += 1
        case "Down": location.y -= 1

        case "Left": location.x -= 1
        case "Right": location.x += 1
        default: break
        }
    }
}

let aRobot = Robot()
aRobot.move("up")
aRobot.move("left")
aRobot.robotLocation() // Always "0 by 0"

2 Answers

Hi Ryan,

It's because you're using case sensitive strings "up" vs "Up". This fixes it:

let aRobot = Robot()
aRobot.move("Up")
aRobot.move("Left")
aRobot.robotLocation()

Awesome! I thought it might be something small. Thank you.

No problems :)