Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy Optional Property Always nil?

Tags:

swift

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.

like image 223
Adam Spindler Avatar asked Jun 25 '14 05:06

Adam Spindler


1 Answers

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)
like image 99
Jereme Avatar answered Oct 15 '22 12:10

Jereme