Is there a reason that the following code always prints out nil?
class Foo
{
@lazy var bar: Int? = 5
}
println(Foo().bar)
I would think that when the bar property is accessed it would be initialized to 5.
Sweeping aside why you'd want to do this, the issue here is that you need to provide a lazy property an initializer it can use when it is first called. The correct way to author your above code is:
class Foo {
lazy var bar = Int(5)
}
print(Foo().bar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With