Site icon CodeWithSwift

Lazy Properties

A lazy property is a property whose initial value is not calculated until the first time it is accessed.

class Example {
    lazy var greeting: String = {
        print("Hello CodewithSwift")
        return "Hello, Swift!"
    }()
}

let example = Example()
print("Before accessing the lazy property")
print(example.greeting) // Hello CodewithSwift
print(example.greeting) // This will reuse the initialized value
class ViewController {
    lazy var label: UILabel = {
        let label = UILabel()
        label.text = "Label"
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
}

let vc = ViewController()
print(vc.label.text ?? "") // Accesses and initializes the label
Exit mobile version