read

One of the common UIKit pattern is to initialize and configure controls in this way:

class MainViewController: UIViewController {
    private let myButton: UIButton = {
        let x = UIButton()
        x.setImage(..., for: [])
        x.addTarget(self, action: #selector(foo(_:)), for: .touchUpInside)
        ...
        return x
    }()
}

I have been using that a lot because it contains all the configurations in 1 place.

But starting from Swift 5.6, there will be a warning.

‘self’ refers to the method MainViewController.self, which may be unexpected

If you auto fix for this case, then the app will crash.

We do really want to refer self to the instance of the view controller.

Solution

The easy fix is to change the let declaration to lazy var!

private lazy var myButton: UIButton = ...

That will remove the warning.

Don’t ask me why self is different between a lazy var and a let..


Image

@samwize

¯\_(ツ)_/¯

Back to Home