Eric
Eric

Reputation: 893

lazy instantiation of `textColor` in `UILabel` throws an error

If I uncomment self.numberLabel.textColor = UIColor.black, the build compiles but crashes in the simulator.

 lazy public var numberLabel: UILabel = {
        self.numberLabel.textColor = UIColor.black
        return UILabel(frame: CGRect.init(x: 10, y: 40, width: self.bounds.size.width, height: 20))
    }()

The error states: "EXC_BAD_ACCESS".

Upvotes: 1

Views: 331

Answers (2)

Jack
Jack

Reputation: 14339

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

Sample snippet - Swift 3.x

 lazy public var numberLabel: UILabel = {
    let label = UILabel(frame: CGRect(x: 20, y: 20, width: 200, height: 21))
    label.textColor = UIColor.black
    return label
}()



 override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(numberLabel)
        numberLabel.text = "Good"
}

Upvotes: 2

Andre
Andre

Reputation: 1145

You are referring to numberLabel before you set it, best approach would be:

lazy public var numberLabel: UILabel = {
    let label = UILabel(frame: CGRect.init(x: 10, y: 40, width:     self.bounds.size.width, height: 20))
    label.textColor = UIColor.black
    return label
}()

As you can see the first "let label = " create the label, then all initialisations can be performed (like the textcolor), finally we return the label, to be assigned to the lazy property.

Upvotes: 1

Related Questions