According to swift language guide's Inheritance chapter, I tried to code compuputed peoperty in subclass. When I set newValue to the property of the class's instance, the setter seemed to work, while the property value did not convert into the newValue.
class Vehicle {
var currentSpeed = 1.0
var description: String {
return "The current speed is \(currentSpeed) miles per hour"
}
func makeNoise() {
}
}
class Car: Vehicle {
var gear = 0
override var description: String {
return super.description + " in gear \(gear)"
}
}
class AutomaticCar: Car {
override var currentSpeed: Double {
get {
return super.currentSpeed
}
set {
gear = Int(newValue/10) + 1
}
}
}
let automaticCar = AutomaticCar()
automaticCar.currentSpeed = 12.0
print(automaticCar.currentSpeed)//It prints "1.0"
print(automaticCar.description)//It prints "The current speed is 1.0 miles per hour in gear 2"
The property value of automaticCar.currentSpeed is still "1.0" rather than "12.0", while the instance's gear property seems to effect. I have searched but could't find the answer, what principle leads to this situation?
Further question:
class A {
var test1 = 1
var test2 = 2
var sum: Int {
get {
return test1 + test2
}
set {
test1 = newValue - test2
}
}
}
var a = A()
print(a.sum)
a.sum = 4
print(a.sum)//It ptints "4"
print(a.test1)//It prints "2"
In this case, I don't need to set the value of new sum property deliberately, What's the differece between two cases?