[英]swift: Is correct to use stored properties as computed properties
我試圖實現這個Objective-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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.