swift:将存储的属性用作计算属性是正确的 [英] swift: Is correct to use stored properties as computed properties
问题描述
我试图实现这个目标-c代码
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;
}
为什么我要用它?从很多地方调用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.
所以我尝试创建存储的属性,并使用getter方法检查是否已创建。
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
但这似乎有效:
class MyClass {
@lazy var customView: NSView = {
let view = NSView()
// customize view
return view
}()
}
这篇关于swift:将存储的属性用作计算属性是正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!