← 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.
Syntax
swift
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

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

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
// 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. #}
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.