Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lazy attribute in Swift equivalent to lazy Init getter in Objective C

Is the lazy attribute in Swift equivalent to overriding the getter with a lazy loading pattern in Objective C?

like image 282
7c9d6b001a87e497d6b96fbd4c6fdf Avatar asked Jun 03 '14 19:06

7c9d6b001a87e497d6b96fbd4c6fdf


3 Answers

From the docs:

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy attribute before its declaration.

So, mostly, yes.

You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy.”

Remember that on Swift you have the option to declare custom getters and setters for your properties:

var name : String?{
  get{
    return "Oscar"
  }
  set(newValue){

  }
}
like image 87
Oscar Swanros Avatar answered Nov 15 '22 04:11

Oscar Swanros


Referring to this:

lazy var x = SomeFunction()

The closest equivalent in Objective-C would be something like:

@property BOOL xHasBeenSet;
@property id x;

- (id)x
{
    if (!self.xHasBeenSet) {
        self.x = SomeFunction();
    }
    return x;
}

- (void)setX:(id)x
{
    _x = x;
    self.xHasBeenSet = YES;
}

Here you would only see SomeFunction called the first time you read x, but only if you don't set x first. It's important to note that there is only one code path where the right side gets called and it never resets back to xHasBeenSet = NO.

like image 44
Brian Nickel Avatar answered Nov 15 '22 05:11

Brian Nickel


mainly yes-- it can't be a computed property though

like image 42
Daij-Djan Avatar answered Nov 15 '22 03:11

Daij-Djan