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

我试图实现这个目标-c代码

@property (strong) UIView *customView; -(UIView*)customView { if (!customView){ self.customView = [[UIView alloc]init]; self.customView.backgroundColor = [UIColor blueColor]; } return customView; } 

我为什么要用这个? 从很多地方调用customView,所以我们必须在所有地方检查这个条件。 为了避免这种重复,我写了这个。

所以我尝试创建存储的属性,并使用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 } } 

它是否正确? 或任何其他方法来做到这一点?

注意:上述代码没有警告或错误。 但与存储和计算属性混淆。 请让我说清楚。

不确定原因,但是与计算属性结合的惰性变量会导致错误:

 'lazy' attribute may not be used on a computed property 

但这似乎有效:

 class MyClass { @lazy var customView: NSView = { let view = NSView() // customize view return view }() } 

这被称为懒惰的财产。 只需将其声明为任何其他存储属性,但使用@lazy修饰符。 当有人第一次尝试获取它时,将创建该对象。 你不需要自己写那些东西。

请参阅Swift Book中的 “Lazy Stored Properties”。 你只需写:

 @lazy var customView = UIView() 

在swift 2.1中应该是以下等价物:

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

另外,我将编写原始的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; }