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

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

markup
struct Player {
    var name: String
    var health: Int = 100
}
let hero = Player(name: "Hero")
print("\(hero.name) has \(hero.health) health")

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

markup
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)")
Common Mistakes
  1. Confusing a stored property (holds an actual value) with a computed property (calculates a value on access) -- they look similar but behave very differently.
  2. Forgetting a let property can only be set once, either at declaration or inside an initializer, never reassigned afterward.
  3. Trying to give a stored property a default value that depends on self before 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.
  • let properties can only be set once; var properties 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:

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.