2016-09-27 43 views
-2

我如何使用一個變量didSet財產以外的方法我如何使用`從方法之外didSet`屬性變量

這項工作的

override func viewWillAppear(_ animated: Bool) { 
    var myString = "sadf" { 
     didSet{ 
      print("myString did change from "+oldValue+" to "+myString) 
     } 
    } 
} 

但我要做到這一點

//add var outside of method 
var myString:String! 

override func viewWillAppear(_ animated: Bool) { 
    //call variable inside of method 
    myString = "sadf" { 
     didSet{ 
      print("myString did change from "+oldValue+" to "+myString) 
     } 
    } 
} 
+2

你「想做到這一點「對我來說毫無意義。請解釋你想要發生的事情。如果你只是想在'viewWillAppear'中打印一些東西,然後調用'print'。 –

+2

你到底在做什麼? – milesper

+0

我試圖從'funcs'監視'viewWillAppear'中變量的變化。可以說'func1'改變了'var'我想知道在'func2'中唯一的方法就是我知道這是'var'不在'viewWillAppear'裏面# – pprevalon

回答

2

你可以爲方法外的屬性定義didSet。這應該工作:

var myString:String = "oldString" { 
    didSet(oldValue) { 
     print("myString did change from "+oldValue+" to "+myString) 
    } 
} 

override func viewWillAppear(_ animated: Bool) { 
    myString = "sadf" 
    myString = "secondCall" 
} 

輸出將是這個樣子:

myString did change from to sadf 
myString did change from sadf to secondCall 

欲瞭解更多信息,請閱讀有關財產觀察員章蘋果文檔中:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

0

只需將整個didSet結構陪定義爲全局myString,因爲你擁有它。沒有法律說didSet只適用於一個財產;它可以應用於全局變量,甚至可以應用於局部變量(儘管誰知道爲什麼要這麼做)!這是完全合法的:

var myString : String! { 
    didSet { 
     print("myString changed") 
    } 
} 
override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(animated) 
    myString = "asdf" 
} 
+0

@Hamish如果你知道OP在說什麼你比我做得更好。 – matt

+0

@matt你的回答是正確的,那正是我想要實現的。還有另一位用戶在你面前提供了相同的答案。謝謝 – pprevalon

+0

@pprevalon沒問題。 – matt

0

你可以做的是,聲明另一個lazy var持有任你挑選舊/新值,並將其賦值在viewWillAppear方法象下面這樣:

lazy var changedString = String() 
var myString = "sadf" { 
    didSet { 
     print("myString did change from "+oldValue+" to "+myString) 
     changedString = myString 
    } 
} 
override func viewWillAppear(_ animated: Bool) { 
    myString = "this got changed" 
} 
相關問題