25

In Swift, When using [weak self] in, should I double up on it when nested inside another closure.

Example:

override func viewDidLoad() {
    super.viewDidLoad()

    makeAPICall() { [weak self] in

        self?.finishedAPICall = true

        DispatchQueue.main.async { [weak self] in
            // random code with self
            self?.view.layoutIfNeeded()
        }
    }
}

func makeAPICall(completion: () -> Void) {}

The outermost [weak self] makes all the following self's optional no matter what. Does this mean that it is handling holding it in memory inside of the nested closures all the way through as well? If I am using self in both areas, do I need it in both?

Anton Belousov
  • 1,140
  • 15
  • 34
Sethmr
  • 3,046
  • 1
  • 24
  • 42
  • 1
    Compare http://stackoverflow.com/questions/17104634/referring-to-weak-self-inside-a-nested-block. – Martin R Feb 10 '17 at 21:00
  • 7
    Also http://stackoverflow.com/q/41991467/2976878. The simple answer is no, you don't need to double them up – the outermost one is sufficient. – Hamish Feb 10 '17 at 21:01
  • 1
    See [Do capture lists of inner closures need to redeclare `self` as `weak` or `unowned`?](http://stackoverflow.com/q/38739129/1271826) – Rob Feb 10 '17 at 21:02
  • 2
    Really I think all 3 Q&As answer the question – we should vote to close as dupe with each of them. – Hamish Feb 10 '17 at 21:10
  • What about unowned self? Would it function exactly the same? – Sethmr Feb 10 '17 at 22:52
  • 1
    They don't answer me... The first link is in ObjC which is often quite different mechanically when it comes to issues like this. The second link handles that I don't need it in the outermost, but is just having it on the outermost good enough is my big question??? Also, the third one just does not have a direct answer. I am calling on someone to answer this super good in Swift to make this the chosen thread =P – Sethmr Feb 10 '17 at 23:05
  • 1
    @Sethmr `unowned` is the same – you just need it on the outermost closure, not the inner one. If the outer closure captures `self` as `unowned` or `weak`, that's also how the inner closure by default captures it. – Hamish Feb 10 '17 at 23:12
  • 1
    @Sethmr Although I'm not sure where you got "*I don't need it in the outermost*" from [the second Q&A](http://stackoverflow.com/q/41991467/2976878) – my answer said "*If however, the outer closure has already weakly captured `self`, then the inner closure will already have a weak reference to `self`, thus adding `[weak self]` to the inner closure will have no effect.*" – Hamish Feb 10 '17 at 23:14
  • @Hamish thanks for that – Sethmr Feb 21 '17 at 23:47

0 Answers0