您好我最近开始学习swift,在阅读继承章节时我遇到了这个问题,所以我创建了一个车辆类作为我的超级类和一个汽车类作为我的子类,汽车类继承自车辆类和之后我创建了一个automaticCar类作为继承自car类的另一个子类(如果有任何歧义,请查看代码),所以当我尝试覆盖dangerText时,似乎Xcode跳过代码并且不会更改dangerText: - ( 请告诉我,如果我做错了什么,我不是在寻找替代方法,因此请通过覆盖解决方案更正我的代码来回答 提前谢谢!
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)
答案 0 :(得分:0)
您在 AutomaticCar 类中犯了一个小错误。在该类中,无需覆盖 dangerText ,而不是在将新值设置为 currentSpeed 时,只需更新dangerText,如下所示...
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)
}
}
}
}
立即检查 dangerText 是否包含给定currentSpeed和maxSpeed的说明。