Swift iOS tips
- qmshahzad
- Feb 5, 2025
- 1 min read
Swift iOS Tip: Use weak Self in Closures to Prevent Retain Cycles
When using closures in Swift, always be mindful of retain cycles, especially when referencing self. If a closure captures self strongly, it can lead to memory leaks.
✅ Correct Way (Using [weak self])
class MyViewController: UIViewController { var myTimer: Timer?
func startTimer() { myTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in self?.updateUI() } }
func updateUI() { print("UI Updated") }}
Here, [weak self] prevents a retain cycle by ensuring self is only weakly referenced inside the closure.
❌ Incorrect Way (Strong Reference)
myTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in self.updateUI() // Strong reference to `self`, causing a retain cycle}
This would cause self to be strongly retained, potentially leading to a memory leak.
Rule of Thumb:
Use [weak self] when self could cause a retain cycle.
If self is needed throughout the closure, use [unowned self] if you are sure self won’t be nil.
Comments