Bird
Raised Fist0
Swiftprogramming~10 mins

Deinitializers for cleanup in Swift - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Deinitializers for cleanup
Create instance
↓
Use instance
↓
Instance no longer needed
↓
Deinitializer called
↓
Cleanup done
↓
Memory freed
When an instance is no longer needed, Swift calls its deinitializer to clean up resources before freeing memory.
Execution Sample
Swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
        print("\(name) is initialized")
    }
    deinit {
        print("\(name) is being deinitialized")
    }
}
var person: Person? = Person(name: "Anna")
person = nil
This code creates a Person instance, then sets it to nil, triggering the deinitializer to run.
Execution Table
StepActionInstance StateOutput
1Create Person instance with name 'Anna'Person(name: "Anna") exists"Anna is initialized"
2person variable holds the instancePerson(name: "Anna") exists
3Set person = nil (remove reference)No instance referenced"Anna is being deinitialized"
4Instance deinitialized and memory freedNo instance
💡 person set to nil, no references remain, deinitializer runs and instance is cleaned up
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
personnilPerson(name: "Anna")Person(name: "Anna")nilnil
Key Moments - 2 Insights
Why does the deinitializer run only after setting person to nil?
Because the instance is kept alive as long as 'person' references it. When 'person' is set to nil (see execution_table step 3), no references remain, so deinit runs.
Can we call deinit manually?
No, Swift calls deinit automatically when the instance is about to be destroyed, as shown in step 3 and 4 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 1?
A"Anna is initialized"
B"Anna is being deinitialized"
CNo output
DError
💡 Hint
Check the Output column at Step 1 in the execution_table.
At which step does the instance get deinitialized?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Action and Output columns in the execution_table for when deinit message appears.
If we never set person to nil, what happens to the deinitializer?
AIt runs immediately after initialization
BIt never runs because the instance is still referenced
CIt runs twice
DIt runs before initialization
💡 Hint
Refer to variable_tracker and execution_table steps showing when references are removed.
Concept Snapshot
Deinitializers run automatically when an instance is about to be destroyed.
Use deinit to clean up resources like files or network connections.
Deinit cannot be called manually.
Instance must have no references for deinit to run.
Setting variables to nil removes references and triggers deinit.
Full Transcript
This visual trace shows how Swift calls a deinitializer to clean up an instance. First, a Person instance named 'Anna' is created and initialized, printing a message. The variable 'person' holds this instance. When 'person' is set to nil, the instance has no references left. At this moment, Swift automatically calls the deinitializer, printing a cleanup message. Finally, the instance is removed from memory. This process ensures resources are freed properly without manual intervention.

Practice

(1/5)
1. What is the main purpose of a deinitializer in Swift?
easy
A. To clean up resources before an object is destroyed
B. To initialize properties when an object is created
C. To manually call a function on an object
D. To create a new instance of a class

Solution

  1. Step 1: Understand what a deinitializer does

    A deinitializer runs automatically just before an object is destroyed to clean up resources like files or network connections.
  2. Step 2: Compare options with the purpose

    Only To clean up resources before an object is destroyed correctly describes this cleanup role. Options B and D describe initializers or object creation, and C is incorrect because deinitializers cannot be called manually.
  3. Final Answer:

    To clean up resources before an object is destroyed -> Option A
  4. Quick Check:

    Deinitializer purpose = cleanup before destruction [OK]
Hint: Deinitializer cleans up just before object is removed [OK]
Common Mistakes:
  • Confusing deinitializer with initializer
  • Thinking deinitializers can be called manually
  • Assuming deinitializers take parameters
2. Which of the following is the correct syntax for a deinitializer in a Swift class?
easy
A. func deinitializer() { }
B. func deinit() { }
C. init deinit() { }
D. deinit { }

Solution

  1. Step 1: Recall Swift deinitializer syntax

    In Swift, a deinitializer is declared with the keyword deinit without parentheses or parameters.
  2. Step 2: Check each option

    deinit { } matches the correct syntax: deinit { }. Options B, C, and D incorrectly use func or parentheses.
  3. Final Answer:

    deinit { } -> Option D
  4. Quick Check:

    Deinitializer syntax = deinit { } [OK]
Hint: Deinitializer uses just 'deinit' keyword with braces [OK]
Common Mistakes:
  • Adding parentheses after deinit
  • Using 'func' keyword with deinit
  • Trying to name the deinitializer function
3. What will be printed when the following Swift code runs?
class FileHandler {
    let filename: String
    init(filename: String) {
        self.filename = filename
        print("Opening file: \(filename)")
    }
    deinit {
        print("Closing file: \(filename)")
    }
}

func useFile() {
    let handler = FileHandler(filename: "data.txt")
}

useFile()
medium
A. Opening file: data.txt Closing file: data.txt
B. Opening file: data.txt
C. Closing file: data.txt
D. No output

Solution

  1. Step 1: Trace object creation and deinitialization

    When useFile() runs, it creates a FileHandler instance, printing "Opening file: data.txt". When the function ends, the local handler is destroyed, triggering the deinitializer which prints "Closing file: data.txt".
  2. Step 2: Confirm output order

    First the initializer message, then the deinitializer message appear in order.
  3. Final Answer:

    Opening file: data.txt Closing file: data.txt -> Option A
  4. Quick Check:

    Init prints open, deinit prints close [OK]
Hint: Deinit runs after object goes out of scope [OK]
Common Mistakes:
  • Assuming deinit runs immediately after init
  • Thinking deinit never runs for local variables
  • Ignoring print statements in deinit
4. Identify the error in this Swift class related to deinitializers:
class Connection {
    var isOpen = false
    deinit() {
        if isOpen {
            print("Closing connection")
        }
    }
}
medium
A. Deinitializer cannot access instance variables
B. Deinitializer must return a value
C. Deinitializer cannot have parentheses
D. Deinitializer must be marked with 'func'

Solution

  1. Step 1: Check deinitializer syntax

    In Swift, deinitializers are declared without parentheses or parameters. The code incorrectly uses deinit() with parentheses.
  2. Step 2: Verify other options

    Deinitializers do not return values, can access instance variables, and do not use the func keyword. So options A, B, and D are incorrect.
  3. Final Answer:

    Deinitializer cannot have parentheses -> Option C
  4. Quick Check:

    Deinit syntax = no parentheses [OK]
Hint: Deinit never uses parentheses or func keyword [OK]
Common Mistakes:
  • Adding parentheses to deinit
  • Expecting return values from deinit
  • Using 'func' keyword with deinit
5. You have a class that manages a network connection and a file handle. How should you use a deinitializer to ensure both resources are properly closed when the object is destroyed?
class ResourceHandler {
    var connection: NetworkConnection?
    var file: FileHandle?

    init(connection: NetworkConnection?, file: FileHandle?) {
        self.connection = connection
        self.file = file
    }

    deinit {
        // What should go here?
    }
}
hard
A. Do nothing; Swift cleans up automatically
B. Call connection.close() and file.close() inside deinit if they are not nil
C. Call init() again inside deinit to reset resources
D. Set connection and file to nil inside deinit

Solution

  1. Step 1: Understand resource cleanup in deinitializer

    Deinitializers are used to release resources like network connections and files. You should explicitly close these resources if they exist before the object is destroyed.
  2. Step 2: Evaluate options for cleanup

    Call connection.close() and file.close() inside deinit if they are not nil correctly calls close() methods on both resources if they are not nil. Set connection and file to nil inside deinit only sets references to nil but does not close resources. Call init() again inside deinit to reset resources is invalid because calling init inside deinit is not allowed. Do nothing; Swift cleans up automatically is incorrect because Swift does not automatically close external resources.
  3. Final Answer:

    Call connection.close() and file.close() inside deinit if they are not nil -> Option B
  4. Quick Check:

    Deinit must close resources explicitly [OK]
Hint: Close resources explicitly in deinit before object destruction [OK]
Common Mistakes:
  • Assuming setting variables to nil closes resources
  • Trying to call init inside deinit
  • Ignoring resource cleanup in deinit
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