Bird
Raised Fist0
Swiftprogramming~10 mins

Classes are reference types in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Classes are reference types
Create instance A
↓
Assign instance A to variable a
↓
Assign variable a to variable b
↓
Modify property via b
↓
Check property via a
↓
Both a and b show same updated value
This flow shows how assigning a class instance to another variable copies the reference, so both variables point to the same object.
Execution Sample
Swift
class Person {
    var name: String
    init(name: String) { self.name = name }
}

let a = Person(name: "Alice")
let b = a
b.name = "Bob"
print(a.name)
This code creates a Person instance, assigns it to two variables, changes the name via one variable, and prints the name via the other to show shared reference.
Execution Table
StepActionVariable aVariable bOutput
1Create Person instance with name 'Alice'Person(name: "Alice")nil
2Assign instance to variable aPerson(name: "Alice")nil
3Assign variable a to variable b (copy reference)Person(name: "Alice")Person(name: "Alice")
4Change b.name to 'Bob'Person(name: "Bob")Person(name: "Bob")
5Print a.namePerson(name: "Bob")Person(name: "Bob")Bob
💡 Execution ends after printing 'Bob', showing both variables reference the same object.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
anilPerson(name: "Alice")Person(name: "Alice")Person(name: "Alice")Person(name: "Bob")Person(name: "Bob")
bnilnilnilPerson(name: "Alice")Person(name: "Bob")Person(name: "Bob")
Key Moments - 2 Insights
Why does changing b.name also change a.name?
Because both a and b point to the same Person instance (see execution_table step 4), changing the property via b affects the same object a refers to.
Does assigning a to b create a new Person object?
No, assigning a to b copies the reference, not the object itself (see execution_table step 3). Both variables share the same instance.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what is the name property of the object referenced by a?
Anil
B"Alice"
C"Bob"
DUndefined
💡 Hint
Check the 'Variable a' column at step 4 in the execution_table.
At which step do variables a and b first reference the same Person instance?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at when variable b gets assigned in the execution_table.
If we changed b.name to "Charlie" instead of "Bob", what would a.name be at the end?
A"Alice"
B"Charlie"
C"Bob"
Dnil
💡 Hint
Since a and b reference the same object, changing b.name changes a.name too (see variable_tracker).
Concept Snapshot
Classes are reference types in Swift.
Assigning a class instance to a new variable copies the reference, not the object.
Changing properties via one variable affects the same shared object.
Use 'class' keyword to define reference types.
This differs from structs which are value types.
Full Transcript
This example shows that classes in Swift are reference types. When you create an instance of a class and assign it to a variable, that variable holds a reference to the object. If you assign that variable to another variable, both variables point to the same object. Changing a property through one variable changes it for the other because they share the same instance. This is different from value types like structs, where assignment copies the data. The execution table traces each step: creating the instance, assigning variables, modifying properties, and printing the result. The variable tracker shows how both variables reference the same object throughout. Understanding this helps avoid confusion when working with classes.

Practice

(1/5)
1. What happens when you assign an instance of a class to another variable in Swift?
easy
A. A new copy of the object is created.
B. Both variables refer to the same object in memory.
C. The original object is deleted.
D. The variables become constants automatically.

Solution

  1. Step 1: Understand class assignment behavior

    In Swift, classes are reference types, so assigning one instance to another variable copies the reference, not the object.
  2. Step 2: Effect of assignment on variables

    Both variables point to the same memory location, so changes via one variable affect the other.
  3. Final Answer:

    Both variables refer to the same object in memory. -> Option B
  4. Quick Check:

    Classes are reference types = A [OK]
Hint: Class assignment copies reference, not object [OK]
Common Mistakes:
  • Thinking a new object is created on assignment
  • Confusing classes with structs (value types)
  • Assuming variables become constants automatically
2. Which of the following is the correct way to declare a class in Swift?
easy
A. class Dog: String { var name }
B. struct Dog { var name: String }
C. class Dog { var name: String }
D. func Dog() { var name: String }

Solution

  1. Step 1: Identify correct class syntax

    In Swift, a class is declared using the keyword 'class' followed by the class name and curly braces containing properties.
  2. Step 2: Check each option

    class Dog { var name: String } correctly declares a class with a property. struct Dog { var name: String } declares a struct, not a class. class Dog: String { var name } has invalid syntax with inheritance from String and missing property type. func Dog() { var name: String } uses 'func' which is for functions, not classes.
  3. Final Answer:

    class Dog { var name: String } -> Option C
  4. Quick Check:

    Correct class syntax = A [OK]
Hint: Use 'class' keyword and braces for class declaration [OK]
Common Mistakes:
  • Using 'struct' instead of 'class'
  • Incorrect inheritance syntax
  • Using 'func' instead of 'class'
3. What will be printed by the following Swift code?
class Counter {
  var count = 0
}

let a = Counter()
let b = a
b.count = 5
print(a.count)
medium
A. 0
B. Compilation error
C. nil
D. 5

Solution

  1. Step 1: Understand reference assignment

    Variable 'b' is assigned to 'a', so both refer to the same Counter instance.
  2. Step 2: Effect of changing 'b.count'

    Changing 'b.count' to 5 changes the shared object's property, so 'a.count' also becomes 5.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Class references share data = 5 [OK]
Hint: Changing one reference changes all references [OK]
Common Mistakes:
  • Assuming 'a.count' stays 0 after changing 'b.count'
  • Expecting a compilation error
  • Confusing with value type behavior
4. Identify the error in this Swift code snippet:
class Person {
  var name: String
}

let p1 = Person()
p1.name = "Alice"
medium
A. Class Person cannot be instantiated with 'let'.
B. Cannot assign value to 'name' because it is a constant.
C. Missing initializer for 'name' property in class Person.
D. No error; code runs fine.

Solution

  1. Step 1: Check class property initialization

    The class Person has a non-optional property 'name' without an initial value or initializer.
  2. Step 2: Understand Swift's requirement for property initialization

    Swift requires all non-optional properties to be initialized before use, either with a default value or in an initializer.
  3. Final Answer:

    Missing initializer for 'name' property in class Person. -> Option A
  4. Quick Check:

    Non-optional properties need initialization = C [OK]
Hint: Non-optional properties must be initialized [OK]
Common Mistakes:
  • Thinking 'let' prevents property assignment
  • Assuming classes can't be instantiated with 'let'
  • Ignoring property initialization rules
5. You want to create a shared settings object that multiple parts of your app can modify and see updates immediately. Which approach best uses Swift classes to achieve this?
hard
A. Create a single instance of a Settings class and pass its reference around.
B. Create multiple instances of a Settings struct and copy them as needed.
C. Use global variables instead of classes for shared data.
D. Use a function that returns a new Settings object every time.

Solution

  1. Step 1: Understand shared mutable state with classes

    Classes are reference types, so a single instance shared by multiple parts allows changes to be seen everywhere.
  2. Step 2: Evaluate options for shared settings

    Create a single instance of a Settings class and pass its reference around. uses one shared instance, which fits the requirement. Create multiple instances of a Settings struct and copy them as needed. uses structs (value types), so copies won't reflect changes. Use global variables instead of classes for shared data. uses globals, which is not recommended for maintainability. Use a function that returns a new Settings object every time. creates new objects each time, so no shared state.
  3. Final Answer:

    Create a single instance of a Settings class and pass its reference around. -> Option A
  4. Quick Check:

    Shared mutable object = B [OK]
Hint: Use one shared class instance for shared mutable data [OK]
Common Mistakes:
  • Using structs which copy data instead of sharing
  • Relying on global variables for sharing
  • Creating new instances instead of sharing one
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard