简体   繁体   English

swift:将存储的属性用作计算属性是正确的

[英]swift: Is correct to use stored properties as computed properties

I'm try to achieve this objective-c code 我试图实现这个Objective-c代码

@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. 从很多地方调用customView,所以我们必须在所有地方检查这个条件。 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. 所以我尝试创建存储的属性,并使用getter方法检查是否已创建。

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. 只需将其声明为任何其他存储属性,但使用@lazy修饰符。 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 . 请参阅Swift Book “Lazy Stored Properties”。 You'd just write: 你刚才写道:

@lazy var customView = UIView()

The equivalent should be the following in swift 2.1: 在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: 另外,我将编写原始的Objective-C代码,如下所示,以避免多次调用customView的getter:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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