Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift lazy stored property versus regular stored property when using closure

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?

like image 646
Boon Avatar asked Nov 28 '25 00:11

Boon


1 Answers

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

like image 157
user3441734 Avatar answered Dec 02 '25 03:12

user3441734



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!