Swift class Inheritance output clarification

51 Views Asked by At

In the following code, why is myRide.drive() printing a class Car instead of "Driving at 200"?

class Car {
    var topSpeed = 200

    func drive() {
        print("Driving at \(topSpeed)")
    }
}

class Futurecar : Car {
    func fly() {
        print ("Flying")
    }
}


let myRide = Car() // Car
myRide.topSpeed // 200
myRide.drive() // Car

let myNewRide = Futurecar() // Futurecar
myNewRide.topSpeed // 200
myNewRide.drive() // Futurecar
myNewRide.fly() // Futurecar

I understand that the class Futurecar is inheriting from the car class. Thanks!

1

There are 1 best solutions below

7
On

I suppose you are doing this in a playground.

In the playground, there is an extra panel on the right there right? I think all these outputs you got are all from the right panel.

The right panel does not necessarily display text printed to the console. When you write a variable, the right panel will display the value of that variable. When you write a method call, the right panel will display the return value of the method. If the method does not return a value, it will display the object on which the method is called.

In this case, drive does not return a value. The right panel displays the object on which it is called on - a FutureCar object.

The above explains the output you get. Now let's move on to see how we can see the text printed. In the bottom of the Xcode window, you will see this:

enter image description here

Click on the button with a triangle inside a rectangle. That will show the console window. The output from your print statements will be displayed here!