Swift - weak self in didSet
Asked Answered
B

2

6

I rarely see people using [weak self] in didSet. Is there a reason for this?

I tried to use [weak self] in my didSet of a variable:

var data: Dictionary<String, Any>! { // [1]
        didSet { [2]
            self?.layoutSubviews()
        }
    }

Either I put [weak self] in at [1] or [2], I still get the error: Use of unresolved identifier weak

Why is that? Is it illegal to use [weak self] for a didSet ?

Regards,

Benzocaine answered 29/4, 2017 at 8:58 Comment(0)
R
20

didSet is not a closure, you cannot use a closure syntax for it.

There is no reason to use weak self there. a didSet handler won't create ownership cycles in the same way a method doesn't create them.

Rossanarosse answered 29/4, 2017 at 9:0 Comment(0)
B
6

Don't do that.

It's nonsensical to use [weak self] because didSet does not capture anything and will never create retain cycles.

Brazzaville answered 29/4, 2017 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.