Swift - is lazy var thread-safe?

前端 未结 1 1807
情话喂你
情话喂你 2020-12-16 04:31

Maybe this question requires a bit of context.

I\'ve been working on my persistence layer using Core Data and found out that Core Data isn\'t thread-safe and thus re

相关标签:
1条回答
  • 2020-12-16 05:04

    From The Swift Programming Language: Properties:

    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.

    lazy var is not thread safe. You can use

    • dispatch_once (runs once per lifetime of the app)
    • a constant (let)
    • the nested struct pattern (typically used for singletons)

    for thread safety. (See this question for some examples.)

    You could also employ your own locking using NSRecursiveLock but that's probably not as efficient as dispatch_once.

    0 讨论(0)
提交回复
热议问题