2016-07-22 74 views
0

您好我最近開始學習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) 
+0

你的代碼是正確的。它在xcode 7.2中工作正常。 – Sahil

+0

它真的很奇怪,它在我的Xcode中無法正常工作,感謝您的回答!減速文本不會打印在我的版本中? –

+0

你收到了什麼錯誤? – Apurv

回答

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的描述一起。

+0

非常感謝Naveen Kumar,它似乎已經成功了! –

+0

是的一點點 –