【发布时间】:2023-04-08 19:10:01
【问题描述】:
根据 swift 语言指南的继承章节,我尝试在子类中编写计算人员。当我将 newValue 设置为类实例的属性时,setter 似乎工作,而属性值没有转换为 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"
automaticCar.currentSpeed 的属性值仍然是“1.0”而不是“12.0”,而实例的 gear 属性似乎生效了。查了也没找到答案,是什么原理导致出现这种情况的?
另一个问题:
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"
在这种情况下,我不需要刻意设置新的sum属性的值,这两种情况有什么区别?
【问题讨论】:
标签: swift inheritance subclass getter-setter