Swift中的lazy属性相当于Objective C中的lazy Init getter [英] lazy attribute in Swift equivalent to lazy Init getter in Objective C

查看:144
本文介绍了Swift中的lazy属性相当于Objective C中的lazy Init getter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Swift中的lazy属性是否相当于在Objective C中使用延迟加载模式覆盖getter?

Is the lazy attribute in Swift equivalent to overriding the getter with a lazy loading pattern in Objective C?

推荐答案

来自文档:


惰性存储属性是一个属性,其初始值在第一次使用之前不会计算。你通过在声明之前写入lazy属性来表示一个惰性存储属性。

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy attribute before its declaration.

所以,大多数情况下是的。

So, mostly, yes.


您必须始终将惰性属性声明为变量(使用var关键字),因为在实例初始化完成之后才可能检索其初始值。常量属性在初始化完成之前必须始终具有值,因此不能声明为惰性。

You must always declare a lazy property as a variable (with the var keyword), because its initial value may not be retrieved until after instance initialization completes. Constant properties must always have a value before initialization completes, and therefore cannot be declared as lazy."

请记住,在Swift上你有为您的属性声明自定义getter和setter的选项:

Remember that on Swift you have the option to declare custom getters and setters for your properties:

var name : String?{
  get{
    return "Oscar"
  }
  set(newValue){

  }
}

这篇关于Swift中的lazy属性相当于Objective C中的lazy Init getter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆