Lazy readonly property in Swift

You can also use a private backing variable that initializes lazily:

var foo : Int { return _foo }
private lazy var _foo :Int = { return 42 }()

Its possible to do this with a computed property and a private struct. There is no need for the lazy keyword on the static var value, as assigning it the result of a block is implicitly lazy.

var foo: Int {
    struct Holder {
        static var value = { return 42 }()
    }
    return Holder.value
}

If readonly and private are synonyms for you in this specific case, then you can make the setter private by explicitly declaring it:

private(set) lazy var foo : Int = { return 42 }()

That's a good compromise between immutability and laziness.

Tags:

Swift