Swift: Properly Using Stored Properties as Computed Properties

I am trying 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 using this? customView is called from many places, so we need to check this condition all over the place. To avoid this duplication, I wrote this.

So, I'm trying to create stored properties, and also use the getter method to check if it is already 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 } } 

It is right? or any other approach for this?

Note. There are no warnings or errors with the above code. But confusion with stored and computed properties. Please let me know.

+6
source share
3 answers

I don’t know why, but lazy variables combined with calculated properties lead to 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 }() } 
+13
source

This is known as a lazy property. Just declare it as any other stored property, but with the @lazy modifier. The object will be created when someone first tries to get it. You do not need to write this for yourself.

See "Lazy Stored Properties" in the Swift Book . You just write:

 @lazy var customView = UIView() 
+2
source

Equivalent should be the following fast 2.1:

 var _customView:UIView? = nil var customView:UIView { if _customView == nil { _customView = UIView.init() _customView?.backgroundColor = UIColor.blueColor() } return _customView! } 

In addition, I will write your objective-C source code as follows to avoid calling the customView receiver 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; } 
0
source

Source: https://habr.com/ru/post/970728/


All Articles