您好我最近開始學習swift,在閱讀繼承章節時我遇到了這個問題,所以我創建了一個車輛類作爲我的超類和汽車類作爲我的子類汽車類繼承自汽車類,之後,我創建了一個autoCar類作爲從汽車類繼承的另一個子類(請參閱代碼,如果有任何歧義),所以當我嘗試覆蓋dangerText時,它似乎像Xcode跳過代碼,並不會改變危險文本:-( 請讓我知道如果我做錯了什麼,我不尋找替代方式,因此請通過糾正我的代碼與覆蓋解決方案回答 在此先感謝!在swift中覆蓋一個實例屬性(幫助)
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)
你的代碼是正確的。它在xcode 7.2中工作正常。 – Sahil
它真的很奇怪,它在我的Xcode中無法正常工作,感謝您的回答!減速文本不會打印在我的版本中? –
你收到了什麼錯誤? – Apurv