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

ios – swift:将存储的属性用作计算属性是正确的,第1张

概述我试图实现这个 Objective-c代码 @property (strong) UIView *customView;-(UIView*)customView{ if (!customView){ self.customView = [[UIView alloc]init]; self.customView.backgroundColor = [UICol 我试图实现这个 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  }()}
总结

以上是内存溢出为你收集整理的ios – swift:将存储的属性用作计算属性是正确的全部内容,希望文章能够帮你解决ios – swift:将存储的属性用作计算属性是正确的所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1099007.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存