Properties
A property is a labeled piece of information stored inside a struct or class, like a car having a color and a speed.
Stored Properties with Default Values
A property can be given a default value right in its declaration, which is used automatically unless overridden by an initializer.
Example: Stored Properties with Default Values
struct Player {
var name: String
var health: Int = 100
}
let hero = Player(name: "Hero")
print("\(hero.name) has \(hero.health) health")
Login to try C/C++/Java/PHP code in the editor
Constant vs Variable Properties
A property declared with let can never change after being set, while one declared with var can be updated at any time.
Example: Constant vs Variable Properties
struct Account {
let id: Int
var balance: Double
}
var account = Account(id: 1, balance: 100.0)
account.balance += 50
print("Account \(account.id) balance: \(account.balance)")
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing a stored property (holds an actual value) with a computed property (calculates a value on access) -- they look similar but behave very differently.
- Forgetting a
letproperty can only be set once, either at declaration or inside an initializer, never reassigned afterward. - Trying to give a stored property a default value that depends on
selfbefore all other properties are initialized.
Chapter Summary
- A stored property holds an actual value as part of an instance.
- Properties can be given default values directly in their declaration.
letproperties can only be set once;varproperties can change afterward.- Both structs and classes can have stored properties.
🔒
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: