Property Observers क्या हैं
एक property observer एक छोटा alarm है जो किसी property की value बदलने से ठीक पहले या ठीक बाद बजता है, ताकि आप इस पर react कर सकें।
In this page:
Syntax
var property: Type = initialValue {
willSet { /* newValue is available */ }
didSet { /* oldValue is available */ }
}
didSet Observer
एक didSet block किसी property की value बदलने के तुरंत बाद चलता है, और implicit oldValue parameter के ज़रिए previous value access कर सकता है।
उदाहरण: didSet Observer
// Define a struct `ScoreTracker`
struct ScoreTracker {
// Call `0` with a trailing closure, storing the result in `score`
var score: Int = 0 {
didSet {
// Print "Score changed from \(oldValue) to \(score)" to the console
print("Score changed from \(oldValue) to \(score)")
}
}
}
// Declare a mutable variable `tracker`, initialized to `ScoreTracker()`
var tracker = ScoreTracker()
tracker.score = 10
tracker.score = 25
Login to try C/C++/Java/PHP code in the editor
willSet Observer
एक willSet block किसी property के बदलने से ठीक पहले चलता है, और implicit newValue parameter के ज़रिए incoming value access कर सकता है।
उदाहरण: willSet Observer
// Define a struct `Thermostat`
struct Thermostat {
// Call `70` with a trailing closure, storing the result in `temperature`
var temperature: Int = 70 {
willSet {
// Print "About to change from \(temperature) to \(newValue)" to the console
print("About to change from \(temperature) to \(newValue)")
}
}
}
// Declare a mutable variable `thermostat`, initialized to `Thermostat()`
var thermostat = Thermostat()
thermostat.temperature = 75
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी computed property में
willSet/didSetजोड़ने की कोशिश करना; observers सिर्फ stored properties (या overridden inherited properties) पर काम करते हैं। - यह भूल जाना कि
didSetOLD valueoldValueके रूप में प्राप्त करता है, जबकिwillSetआने वाली NEW valuenewValueके रूप में प्राप्त करता है। - एक guard condition के बिना property को इसके अपने
didSetके अंदर फिर सेट करना, ज़्यादा complex cases में infinite recursion का जोखिम उठाते हुए।
चैप्टर सारांश
willSetकिसी stored property की value बदलने से ठीक पहले चलता है;didSetठीक बाद चलता है।willSetके अंदर, implicit parameternewValueजिस value को सेट होना है उसे रखता है।didSetके अंदर, implicit parameteroldValueprevious value रखता है।- Property observers सिर्फ stored properties पर लागू होते हैं, computed वाली पर नहीं।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: