Swift ~ Lazy Stored Properties (懒加载)

官方文档 ~ Lazy Stored Properties

Lazy Stored Properties
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 modifier before its declaration.
NOTE
You must always declare a lazy property as a variable (with the var keyword), because its initial value might 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.
Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed.
NOTE
If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.


1、译文及注意的点

  • 延迟存储属性是在第一次使用时才计算初始值的属性。
  • 必须始终将惰性属性声明为变量(使用var关键字)。
  • 如果标记为lazy修饰符的属性被多个线程同时访问,且该属性尚未初始化,则不能保证该属性只初始化一次。
用途
  • 当属性的初始值依赖于外部因素时,且这些外部因素的值在实例初始化完成之前是未知的。

  • 当属性的初始值需要复杂的或计算开销很大时。


2、在OC中实现懒加载

// ClassA.h
@property (nonatomic, copy) NSString *testString;

// ClassA.m
- (NSString *)testString {
     if (!_testString) {
         _testString = @"Hello";
        NSLog(@"只在首次访问输出");
     }
     return _testString;
}

在初始化 ClassA 对象后,_testString 是 nil。只有当首次访问 testString 属性时 getter 方法会被调用,并检查如果还没有初始化的话,就进行赋值。为了方便确认,我们还在赋值时打印了一句 log。我们之后再多次访问这个属性的话,因为 _testString 已经有值,因此将直接返回。


3、在Swift中实现懒加载

class ClassA {
    lazy var str: String = {
        let str = "Hello"
        print("只在首次访问输出")
        return str
    }()
}

4、弥补在Swift中dispatch_once被废弃掉了

class ClassA {
    fileprivate lazy var justOnceTime: Void = {
        print("只希望在该实例中执行一次")
        // ...
    }()
    
    func mayCallManytimes() {
        _ = justOnceTime
    }
}

let b = ClassA()
b.mayCallManytimes()
b.mayCallManytimes()
b.mayCallManytimes()

// output:  只希望在该实例中执行一次
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容