Weak self and unowned self patterns in Swift - Time & Space Complexity
When using weak or unowned self in Swift closures, it's important to understand how this affects the number of operations your program performs.
We want to see how the use of these patterns changes the work done as input grows.
Analyze the time complexity of the following Swift code using weak self in a closure.
class Downloader {
func fetchData(completion: @escaping () -> Void) {
DispatchQueue.global().async { [weak self] in
guard let self = self else { return }
// simulate work
for _ in 0..<1000 { _ = 1 + 1 }
completion()
}
}
}
This code fetches data asynchronously and uses weak self to avoid retain cycles.
Look for loops or repeated actions inside the closure.
- Primary operation: The for-loop running 1000 times inside the closure.
- How many times: Exactly 1000 times per closure execution.
The loop runs a fixed 1000 times regardless of input size, so the work inside the closure stays the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1000 |
| 100 | 1000 |
| 1000 | 1000 |
Pattern observation: The number of operations does not grow with input size; it stays constant.
Time Complexity: O(1)
This means the work done inside the closure does not increase as input size grows; it stays constant.
[X] Wrong: "Using weak self makes the closure run slower as input grows because it adds overhead."
[OK] Correct: The weak self capture only affects memory management, not how many times the loop runs or how much work is done inside the closure.
Understanding how weak and unowned self affect your code helps you write safe, efficient Swift programs and shows you know how to manage memory and performance together.
"What if the loop count inside the closure depended on an input parameter n? How would the time complexity change?"
Practice
weak self inside a closure in Swift?Solution
Step 1: Understand strong reference cycles
Strong reference cycles happen when closures captureselfstrongly, causing memory leaks.Step 2: Role of
Usingweak selfweak selfmakes the reference toselfoptional and allows it to become nil, breaking the cycle.Final Answer:
To prevent strong reference cycles and allowselfto become nil -> Option CQuick Check:
Weak self avoids memory leaks = A [OK]
- Thinking weak self guarantees non-nil self
- Confusing weak with unowned self
- Assuming weak self copies self
self as unowned in a Swift closure?Solution
Step 1: Recall capture list syntax
Swift uses square brackets with capture specifiers beforeinin closures.Step 2: Correct unowned syntax
The correct syntax is[unowned self] into captureselfas unowned.Final Answer:
[unowned self] in -> Option BQuick Check:
Unowned capture syntax = [unowned self] in [OK]
- Swapping order like [self unowned]
- Missing brackets or 'in' keyword
- Using weak instead of unowned when asked
class Example {
var closure: (() -> Void)?
func setup() {
closure = { [weak self] in
print(self == nil ? "nil" : "not nil")
}
}
}
let example = Example()
example.setup()
example.closure?()
What will be printed when example.closure?() is called?Solution
Step 1: Analyze weak self capture
The closure capturesselfweakly, so inside the closureselfis optional.Step 2: Check
Theselflifetimeexampleinstance is still alive whenclosure?()is called, soselfis not nil.Final Answer:
not nil -> Option AQuick Check:
Weak self is alive here = not nil [OK]
- Assuming weak self is always nil
- Confusing weak self with unowned self
- Expecting runtime crash due to optional
class Person {
var name = "Alice"
lazy var greet: () -> Void = {
print("Hello, \(self.name)!")
}
}
let p = Person()
p.greet()
Solution
Step 1: Detect strong reference cycle risk
The closure capturesselfstrongly, andgreetis lazy var, so cycle possible.Step 2: Choose unowned self for non-optional self
Sinceselfwill always exist whengreetis called,unowned selfis safe and avoids optional unwrapping.Final Answer:
Use [unowned self] in closure to avoid strong reference cycle -> Option AQuick Check:
Unowned self for guaranteed self = C [OK]
- Ignoring strong reference cycles
- Using weak self and forcing unwrap unnecessarily
- Thinking no problem exists
Solution
Step 1: Understand lifetime of self and closure
Ifselfwill definitely exist while closure runs,unowned selfis safe and avoids optionals.Step 2: Compare weak vs unowned for this case
weak selfrequires optional unwrapping, butunowned selfassumesselfexists, simplifying code and avoiding leaks.Final Answer:
Useunowned selfbecauseselfwill outlive the closure, avoiding optionals -> Option DQuick Check:
Unowned self for guaranteed lifetime = A [OK]
- Using weak self but not unwrapping safely
- Using strong self causing memory leaks
- Ignoring self capture causing leaks
Ready to prove it?
Pass the test and this pattern moves unknown
