Lazy Initialisation and Retain Cycle

Lazy initialisation and retain cycle

I tried this [...]

lazy var personalizedGreeting: String = { return self.name }()

it seems there are no retain cycles

Correct.

The reason is that the immediately applied closure {}() is considered @noescape. It does not retain the captured self.

For reference: Joe Groff's tweet.

Implementing lazy initialisation in C

In C, there are no references, and you have to type struct, and you have to take care of initialization.

#include <stdbool.h>
struct foo { int a; };
struct foo create_foo();
const struct foo* get_foo() {
static bool initialized = false;
static struct foo x;
if (!initialized) {
initialized = true;
x = create_foo();
}
return &x;
}

To be thread-safe, you can use call_once. Sadly, with a global variable.

#include <threads.h>
struct foo { int a; };
struct foo create_foo();

static struct foo global_x;
static void init_global_x(void) {
global_x = create_foo();
}
const struct foo* get_foo() {
static once_flag global_x_initialized = ONCE_FLAG_INIT;
call_once(&global_x_initialized , init_global_x);
return &global_x;
}

Lazy initialization using self and unown self,

In this code:

lazy var greeting: String = {
return "Hello, my name is \(self.firstName)"
}()

... there is no retained closure. Notice the (). This is just a function, like any other; it is called, not stored. greeting is a String, not a stored closure.

Designated initializer vs lazy initialisation in Objective-C

lazy instantiation is a core concept with objective-c and is used often.

How to create an immutable lazy property?

In short, that's not possible. As per Swift documentation:

Constant properties must always have a value before initialization
completes, and therefore cannot be declared as lazy.

Link: Swift lazy documentation

You can declare child as private(set) so it can only be changed from inside your class.

do we need weak or unowned reference when doing a lazy variable, memory management

The reason you leak memory is because closure will capture self strongly in default and at the same time self hold the closure as a property strongly. It has nothing to do with lazy variable.



Related Topics



Leave a reply



Submit