1

Here I have added code with getter method for one time allocation in obj c. How we will write same code in swift. I need one time allocation. I already seen the computed get and set method, but can't find a solution for this.

@property (nonatomic, strong) UIImageView *bgImageView;

- (UIImageView *)bgImageView{
    if (_bgImageView == nil) {
        _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, width, 277)];
        _bgImageView.image = [UIImage imageNamed:@"imageName"];
        _bgImageView.alpha = 0;
        _bgImageView.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
    }
    return _bgImageView;
}

[self.view addSubview:self.bgImageView];
Arun Kumar P
  • 820
  • 2
  • 12
  • 25

1 Answers1

4

Swift introduced a new concept, lazy property. A lazy property is initialized only when you use it for the first time. Like a custom getter in objective-C, you can also add some logic after creating the object (for example, in your case, setting alpha value, image, and background color)

lazy var bgImageView:UIImageView  = {
    var imageView = UIImageView(frame: CGRectMake(0, 0, width, 27))
    imageView.image = UIImage(named: "imageName")
    imageView.alpha = 0
    imageView.backgroundColor = UIColor(red: 244/255, green:  244/255, blue:  244/255, alpha: 1)
    return imageView
}()

The code is called only once, but Apple warns about multithreading access :

If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.

Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
  • ok , lazy var will allocate only once when first time call used. but are you sure it will allocate only once ? – Arun Kumar P Feb 22 '16 at 07:34
  • Lazy properties are made for delay the initialization and the code will be called only once. I've edited my answer to add an exception from Swift Programming Guide: when multiple thread try to access a lazy property not initialized, it can be allocated multiple time. – Michaël Azevedo Feb 22 '16 at 07:39
  • stackoverflow.com/a/34204555/3400991 this link has perfect answer for ur question. – Shobhakar Tiwari Feb 22 '16 at 07:41
  • @MichaëlAzevedo I got this error for this code . Cannot convert value of type '() -> _' to specified type 'UIImageView' Do we need to add `()` at the end of closure – Arun Kumar P Feb 22 '16 at 07:50
  • Just edited my answer, you have to add '()' at the end of the code. My fault ! – Michaël Azevedo Feb 22 '16 at 07:51