Properties क्या हैं
एक property एक struct या class के अंदर stored information का एक labeled टुकड़ा है, एक car की color और speed होने जैसा।
Syntax
struct TypeName {
var variableProperty: Type // can change
let constantProperty: Type // fixed after init
var withDefault: Type = defaultValue
}
Stored Properties with Default Values
किसी property को इसके declaration में ही एक default value दी जा सकती है, जो किसी initializer द्वारा override न होने तक अपने आप उपयोग होती है।
उदाहरण: Stored Properties with Default Values
// Define a struct `Player`
struct Player {
var name: String
// Declare a mutable variable `health` (an Int), initialized to `100`
var health: Int = 100
}
// Declare a constant `hero`, set to `Player(name: "Hero")`
let hero = Player(name: "Hero")
// Print "\(hero.name) has \(hero.health) health" to the console
print("\(hero.name) has \(hero.health) health")
Login to try C/C++/Java/PHP code in the editor
Constant vs Variable Properties
let से declared property सेट होने के बाद कभी बदल नहीं सकती, जबकि var से declared एक को कभी भी update किया जा सकता है।
उदाहरण: Constant vs Variable Properties
// Define a struct `Account`
struct Account {
let id: Int
var balance: Double
}
// Declare a mutable variable `account`, initialized to `Account(id: 1, balance: 100.0)`
var account = Account(id: 1, balance: 100.0)
account.balance += 50
// Print "Account \(account.id) balance: \(account.balance)" to the console
print("Account \(account.id) balance: \(account.balance)")
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. #}
आम गलतियां
- एक stored property (एक असली value रखता है) को एक computed property (access पर एक value calculate करता है) के साथ confuse करना -- ये similar दिखते हैं लेकिन बहुत अलग behave करते हैं।
- यह भूल जाना कि एक
letproperty सिर्फ एक बार सेट की जा सकती है, या तो declaration पर या एक initializer के अंदर, बाद में कभी reassigned नहीं। - किसी stored property को एक default value देने की कोशिश करना जो बाकी सभी properties initialized होने से पहले
selfपर निर्भर हो।
चैप्टर सारांश
- एक stored property एक instance के हिस्से के रूप में एक असली value रखती है।
- Properties को उनकी declaration में सीधे default values दी जा सकती हैं।
letproperties सिर्फ एक बार सेट की जा सकती हैं;varproperties बाद में बदल सकती हैं।- Structs और classes दोनों में stored properties हो सकती हैं।
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: