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];
2

1 Answer 1

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.

5
  • ok , lazy var will allocate only once when first time call used. but are you sure it will allocate only once ? Feb 22, 2016 at 7: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. Feb 22, 2016 at 7:39
  • stackoverflow.com/a/34204555/3400991 this link has perfect answer for ur question. Feb 22, 2016 at 7: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 Feb 22, 2016 at 7:50
  • Just edited my answer, you have to add '()' at the end of the code. My fault ! Feb 22, 2016 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.