Armin T Armin T - 4 months ago 15
Swift Question

Overriding a instance property in swift (help)

Hi I have recently started learning swift , when was reading the inheritance chapter I came across this problem, so I have created a vehicle class as my super class and a car class as my subclass the car class inherits from vehicle class and after that I have created an automaticCar class as another subclass which inherits from car class (please see code if there is any ambiguity) , so when I try to override the dangerText it seems like Xcode jumps over the code and does not change the dangerText :-(
please let me know if I am doing something wrong , I'm not looking for an alternative way , therefore please answer by correcting my code with an override solution
Thanks in advance !

import Foundation
class viehcle {
//SuperClass viehcle
var currentSpeed = 0
let maxSpeed = 180
var descripion:String{
return "Current speed is \(currentSpeed)"
}
}
class car:viehcle{
//SubClass car inherits from viehcle
var currentGear = 1
var dangerText = ""
//override of description instance property
override var descripion: String{
return ("The current speed is \(super.currentSpeed) and the gear is \(currentGear) \(dangerText)")
}
}
class AutomaticCar:car{
//SubClass AutomaticCar which inherits fom superClass car


//override of dangerText instance property of car
override var dangerText: String{
didSet{
if currentSpeed>maxSpeed{
let slowDown = "Slow Down !"
dangerText = dangerText.stringByAppendingString(slowDown)
}
}
}
//override current speed instance property of car
override var currentSpeed: Int{
didSet{

currentGear = (currentSpeed/40)+1

if currentGear <= 4 {

currentGear = self.currentGear

}
else{
currentGear = 4
}
}
}
}

var myCar = car() // obj/instance created from car class
var myAutomaticCar = AutomaticCar() // obj/instance created from AutomaticCar class
myAutomaticCar.currentSpeed = 300 // set Automatic car's current speed to 300

print(myCar.descripion)
print(myAutomaticCar.descripion)

Answer

You have done a small mistake in the AutomaticCar class. In that class no need to override the dangerText, instead of that when you set the new value to the currentSpeed just update the dangerText as shown below...

class AutomaticCar:car {
    override var currentSpeed: Int {
        didSet {
            currentGear = (currentSpeed/40)+1
            if currentGear <= 4 {
                currentGear = self.currentGear
            }
            else{
                currentGear = 4
            }
            if currentSpeed > maxSpeed {
                let slowDown = "Slow Down !"
                dangerText = dangerText.stringByAppendingString(slowDown)
            }
        }
    }
}

Check now the dangerText will come with the description for the given currentSpeed and maxSpeed.