← Back to Swift Course | Chapter 8: Structs & Classes | Lesson 4 of 9

Properties क्या हैं

एक property एक struct या class के अंदर stored information का एक labeled टुकड़ा है, एक car की color और speed होने जैसा।
Syntax
swift
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

markup
// 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")

Constant vs Variable Properties

let से declared property सेट होने के बाद कभी बदल नहीं सकती, जबकि var से declared एक को कभी भी update किया जा सकता है।

उदाहरण: Constant vs Variable Properties

markup
// 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)")
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. #}
आम गलतियां
  1. एक stored property (एक असली value रखता है) को एक computed property (access पर एक value calculate करता है) के साथ confuse करना -- ये similar दिखते हैं लेकिन बहुत अलग behave करते हैं।
  2. यह भूल जाना कि एक let property सिर्फ एक बार सेट की जा सकती है, या तो declaration पर या एक initializer के अंदर, बाद में कभी reassigned नहीं।
  3. किसी stored property को एक default value देने की कोशिश करना जो बाकी सभी properties initialized होने से पहले self पर निर्भर हो।
चैप्टर सारांश
  • एक stored property एक instance के हिस्से के रूप में एक असली value रखती है।
  • Properties को उनकी declaration में सीधे default values दी जा सकती हैं।
  • let properties सिर्फ एक बार सेट की जा सकती हैं; var properties बाद में बदल सकती हैं।
  • Structs और classes दोनों में stored properties हो सकती हैं।
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.