Correct use of weak 'self' in nested escaping blocks

I would like someone's help to understand the correct use of weak self in nested escaping blocks. It would be great if someone could tell me whether what I'm doing below is correct. Thank you.


import UIKit

class MyClass {
  var closingTimer: Timer?
   
  func f1() {
    /**
     Some work here
      */
  }
   
  func f2() {
    closingTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval.init(5), repeats: true, block: { [weak self] (t: Timer) in
      /**
       Some work here
        */
       
      if let _ = self {
        DispatchQueue.main.async { [weak self] in
          self?.f1()
        }
      }
    })
       
  }
}

Accepted Reply

Repeating [weak self] is not an issue and will make code more robust to possible changes in the future.

It is even better (to avoid hidden retain cycle) as explained here: https://github.com/apple/swift-evolution/blob/main/proposals/0365-implicit-self-weak-capture.md

Note that you will soon be authorised to simply write (same reference)

 if let self {
        DispatchQueue.main.async { [weak self] in
          f1()  // No more self?.
        }

Replies

Repeating [weak self] is not an issue and will make code more robust to possible changes in the future.

It is even better (to avoid hidden retain cycle) as explained here: https://github.com/apple/swift-evolution/blob/main/proposals/0365-implicit-self-weak-capture.md

Note that you will soon be authorised to simply write (same reference)

 if let self {
        DispatchQueue.main.async { [weak self] in
          f1()  // No more self?.
        }