#51: Lazy Stored Properties in Swift

A lazy stored property is initialized only when it is used for the first time. This is useful when the value is expensive to create or might never be needed.

final class ImageViewModel {
    lazy var formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()
}

Without lazy, the formatter would be created as soon as the object is initialized. With lazy, that work is deferred until formatter is actually read.

Because lazy properties depend on instance state, they must be declared with var, not let.


I'm also on Twitter and GitHub.

Subscribe via RSS.