2016-02-01 49 views
3

我想重寫屬性觀察器並調用「super.didSet」。那可能嗎?覆蓋didSet

class Foo { 
    var name: String = "" { didSet { print("name has been set") } } 
} 

class Bar: Foo { 
    override var name: String = "" { 
     didSet { 
      print("print this first") 
      // print the line set in the superclass 
     } 
    } 
} 
+0

什麼你想從這些印刷(...)■看到輸出? – Ismail

回答

6

我曾嘗試你的代碼在一個操場,並獲得和錯誤

與變量的getter/setter方法不能和初始值。

所以我剛剛從orverriding變量中刪除了=""。如下圖所示:

class Foo { 
    var name: String = "" { didSet { print("name has been set") } } 
} 

class Bar: Foo { 
    override var name: String { 
     didSet { 
      print("print this first") 
      // print the line set in the superclass 
     } 
    } 
} 

let bar = Bar() 
bar.name = "name" 

,這就是我在CONSOL有:

name has been set 
print this first