Properties
A property is a labeled piece of information stored inside a struct or class, like a car having a color and a speed.
Syntax
struct TypeName {
var variableProperty: Type // can change
let constantProperty: Type // fixed after init
var withDefault: Type = defaultValue
}
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
// 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
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
// 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. #}
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: