top of page

Swift iOS tips

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.

 
 
 

Recent Posts

See All
{{ $('Get Ready Post').item.json.Title }}

AI agent workflows are shifting enterprise spending. Gartner predicts AI inference costs per agentic workflow will increase more than 5x through 2028 as systems shift from basic LLM prompts to continu

 
 
 
{{ $('Get Ready Post').item.json.Title }}

Cloud-based AI has two persistent problems for mobile developers: latency, because every inference call is a round trip to a server, and privacy, because user data has to leave the device to be proces

 
 
 

Comments


© 2025 by Shahzad. Powered and secured by QMShahzad

bottom of page