【发布时间】:2017-05-19 15:19:40
【问题描述】:
当我学习 swift 时,我发现 Lazy 的概念有点混乱。
惰性属性在类实例需要或访问时初始化
class Employee
{
var name : String
lazy var salary = Salary(Basic : 25000 ,HRA : 3000 , DA : 4000)
lazy var minExperience = 0
init(nameValue :String)
{
name = nameValue
} }
var emp1 = Employee("John") // Here the minExperience and
//salary will be nil as they are not assigned any space =
//emp1.salary.storage = nil , emp1.minExperience.storage = nil
// now access the minExperience
emp1.minExperience // using 1st time and this will return 0 ! emp1.salary.HRA // using 1st time and this will return 3000 !
所以我的问题是:
因为
minExperience和salary没有分配任何存储空间,所以在我们访问它之前,它会将其值存储在哪里 -0或3000???-
惰性属性的一个方面是
当属性的初始值依赖于外部因素时,惰性属性很有用,而外部因素的值在 实例初始化完成。
那为什么 Xcode 强制我们在声明时赋值呢??
- 由于我们已经为 Lazy 属性赋值,显然我们不需要在
init方法中初始化它。
【问题讨论】:
标签: swift properties lazy-evaluation