惯例先看代码
class CloseRange{ var start: Int var end: Int // 非懒加载 var sum1: Int { var res = 0 for i in self.start...self.end { res += i } print("no lazy load") return res } // 懒加载 lazy var sum: Int = { var res = 0 for i in self.start...self.end { res += i } print("lazy load") return res }() init(start: Int,end: Int) { self.start = start self.end = end } } var range = CloseRange(start: 1,end: 10000); range.sum range.sum range.sum range.sum range.sum1 range.sum1 range.sum1 range.sum1
上面代码打印结果
lazy load
no lazy load
no lazy load
no lazy load
no lazy load
看到上面打印结果,非懒加载 sum 加载了4次,懒加载sum1只加载了一次,对于此例子中有大量计算的代码来说,可以节省很多计算时间和硬件资源