Arun Kumar P
Arun Kumar P

Reputation: 900

How write getter method in swift same like objective C, with better ways

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

Upvotes: 1

Views: 84

Answers (1)

Michaël Azevedo
Michaël Azevedo

Reputation: 3896

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.

Upvotes: 4

Related Questions