Memoization of Swift properties

There is a way to reset lazy var if you want. I think it's probably a bug (EDIT: now fixed), but you can access the underlying storage of a lazy var using $__lazy_storage_$_{property_name} and set it to nil. For example:

class A {
    lazy var foo: Int = {
        print("A")
        return 0
    }()
    
    func resetLazy() {
        $__lazy_storage_$_foo = nil
    }
}

let a = A()
print(a.foo)
a.resetLazy()
print(a.foo)

// Prints:
// A
// 0
// A
// 0
4 Likes