Reputation: 17585
I'm try to achieve this objective-c code
@property (strong) UIView *customView;
-(UIView*)customView
{
if (!customView){
self.customView = [[UIView alloc]init];
self.customView.backgroundColor = [UIColor blueColor];
}
return customView;
}
Why am I use this? customView called from many place, so we have to check this condition in all place. To avoid this duplication, I wrote this.
So I'm try to create stored properties and also use getter method to check if already either created or not.
var mainView : UIView? {
get{
if let customView = self.mainView{
return self.mainView
}
var customView : UIView = UIView()
self.mainView = customView
self.mainView.backgroundColor = UIColor(blueColor)
return customView
}
set{
self.mainView = newValue
}
}
Is this correct? or any other approach to do this?
Note: There's no warning or error with above code. But confusion with stored and computed properties. Please make me clear.
Upvotes: 6
Views: 5586
Reputation: 33036
The equivalent should be the following in swift 2.1:
var _customView:UIView? = nil
var customView:UIView {
if _customView == nil
{
_customView = UIView.init()
_customView?.backgroundColor = UIColor.blueColor()
}
return _customView!
}
Also, I will write your original objective-C code as the following so as to avoid calling the getter of customView
multiple times:
@property (strong) UIView *customView;
// @synthesize customView; // make sure you didn't add this line
- (UIView*)customView
{
if (!_customView){
_customView = [[UIView alloc] init];
_customView.backgroundColor = [UIColor blueColor];
}
return customView;
}
Upvotes: 0
Reputation: 6494
Not sure why, but lazy variables combined with computed properties result in an error:
'lazy' attribute may not be used on a computed property
But this seems to work:
class MyClass {
@lazy var customView: NSView = {
let view = NSView()
// customize view
return view
}()
}
Upvotes: 13
Reputation: 100622
This is known as a lazy property. Just declare it like any other stored property but with the @lazy
modifier. The object will be created when somebody first tries to get it. You don't need to write that stuff for yourself.
See 'Lazy Stored Properties' in the Swift Book. You'd just write:
@lazy var customView = UIView()
Upvotes: 2