Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift: Is correct to use stored properties as computed properties

Tags:

ios

swift

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.

like image 426
Mani Avatar asked Jun 12 '14 06:06

Mani


People also ask

Are computed properties stored in Swift?

Computed properties are part of a family of property types in Swift. Stored properties are the most common which save and return a stored value whereas computed ones are a bit different. A computed property, it's all in the name, computes its property upon request.

What is the difference between stored and computed property in Swift?

Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. Computed properties are provided by classes, structures, and enumerations.

What is property in Swift describe computed property with example?

A Swift variable or constant defined inside a class or struct are called properties. For example, class Person { // define properties var name: String = "" var age: Int = 0 ... } Here, inside the Person class we have defined two properties: name - of String type with default value ""

Can we override stored property in Swift?

You can provide a custom getter (and setter, if appropriate) to override any inherited property, regardless of whether the inherited property is implemented as a stored or computed property at source.


1 Answers

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
  }()
}
like image 88
lassej Avatar answered Sep 30 '22 20:09

lassej