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.
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.
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.
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 ""
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.
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
}()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With