2

In Swift, we can set a stored property to use closure:

class Test {
  var prop: String = {
    return "test"
  }()
}

vs

or make lazy stored property use closure:

class Test {
  lazy var prop: String = {
    return "test"
  }()
}

In both cases, the code used to obtain the value for the property is only run once. It seems like they are equivalent.

When should I use lazy stored property versus computed property when using closure with it?

Boon
  • 40,656
  • 60
  • 209
  • 315
  • Actually, both are *stored properties*, not computed properties. – Martin R Nov 24 '15 at 18:56
  • as Martin said, both are stored properties. the value of the first one is evaluated when an instance of class Test is created. the second one, which is lazy, is evaluated 'on demand' when its value is first time required by your code. – user3441734 Nov 24 '15 at 19:07
  • @MartinR Thanks for the correction, will fix question. – Boon Nov 24 '15 at 19:27

1 Answers1

19
import Foundation
struct S {
    var date1: NSDate = {
        return NSDate()
    }()
    lazy var date2: NSDate = {
        return NSDate()
    }()
}

var s = S()
sleep(5)
print( s.date2, s.date1)
/* prints

2015-11-24 19:14:27 +0000 2015-11-24 19:14:22 +0000

*/

both are stored properties, check the real time at which they are evaluated. the lazy property is evaluated 'on demand' when first time the value is needed

user3441734
  • 16,722
  • 2
  • 40
  • 59