简体   繁体   中英

swift: Is correct to use stored properties as computed properties

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.

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
  }()
}

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM