Computed Properties क्या हैं
एक computed property बिल्कुल एक value store नहीं करता -- यह हर बार आपके पूछने पर एक नई value calculate करता है, एक thermometer की current temperature दिखाने जैसा।
Syntax
struct TypeName {
var computed: Type {
get { return value }
set { /* use newValue */ }
}
var readOnly: Type { return value }
}
Read-Only Computed Property
सिर्फ एक get block वाला एक computed property हर access पर अपनी value calculate और return करता है, कुछ भी store किए बिना।
उदाहरण: Read-Only Computed Property
// Define a struct `Rectangle`
struct Rectangle {
var width: Double
var height: Double
var area: Double {
// Return `width * height` from this function
return width * height
}
}
// Declare a constant `rect`, set to `Rectangle(width: 4, height: 5)`
let rect = Rectangle(width: 4, height: 5)
// Print "Area: \(rect.area)" to the console
print("Area: \(rect.area)")
Login to try C/C++/Java/PHP code in the editor
Computed Property with get and set
एक set block जोड़ना आपको एक computed property को assign करने देता है, आमतौर पर नई value को underlying stored properties पर changes में translate करते हुए।
उदाहरण: Computed Property with get and set
// Define a struct `Temperature`
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get { celsius * 9 / 5 + 32 }
set { celsius = (newValue - 32) * 5 / 9 }
}
}
// Declare a mutable variable `temp`, initialized to `Temperature(celsius: 0)`
var temp = Temperature(celsius: 0)
// Print "Fahrenheit: \(temp.fahrenheit)" to the console
print("Fahrenheit: \(temp.fahrenheit)")
temp.fahrenheit = 212
// Print "Celsius after setting F: \(temp.celsius)" to the console
print("Celsius after setting F: \(temp.celsius)")
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. #}
आम गलतियां
- एक read-only computed property (सिर्फ एक
getवाली) में सीधे एक value store करने की कोशिश करना; इसके पास बिल्कुल कोई backing storage नहीं है। - यह भूल जाना कि एक computed property को एक explicit type annotation चाहिए, क्योंकि Swift के infer करने के लिए कोई initial value नहीं है।
- किसी computed property के getter के अंदर expensive logic लिखना जो हर access पर बार-बार चलता है, जब एक stored, precalculated value ज़्यादा efficient हो सकती थी।
चैप्टर सारांश
- एक computed property हर बार access होने पर एक
getblock से अपनी value calculate करता है। - एक optional
setblock एक computed property को assign भी होने देता है। - Computed properties
varसे declared होते हैं, कभीletनहीं, क्योंकि वे stored values नहीं हैं। - ये दूसरी properties से derived values के लिए उपयोगी हैं।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: