Lazy property initialization in Swift

后端 未结 9 1131
深忆病人
深忆病人 2020-12-18 04:25

How would you implement the following pattern in Swift?

The Container class is initialized with a JSON array that contains dictionaries. These dictionar

9条回答
  •  眼角桃花
    2020-12-18 05:06

    You can use Lazy Stored Properties in Swift to implement the Lazy Instantiation pattern. This is done by adding the @lazy attribute before the declaration of the stored property.

    There are two things to keep in mind:

    • Lazy properties must be initialized when declared
    • Lazy properties can only be used on members of a struct or a class (hence why we need to use a DataManager)

    Here's some code you can throw into a Playground to see how the @lazy attribute works

    // initialize your lazily instantiated data
    func initLazyData() -> String[] {
        return ["lazy data"]
    }
    
    // a class to manage the lazy data (along with any other data you want)
    class DataManager {
        @lazy var lazyData = initLazyData()
    
        var otherData = "Other data"
    }
    
    // when we create this object, the "lazy data" array is not initialized
    let manager = DataManager()
    
    // even if we access another property, the "lazy data" array stays nil
    manager.otherData += ", more data"
    manager
    
    // as soon as we access the "lazy data" array, it gets created
    manager.lazyData
    manager
    

    For more information, you can check out the Lazy Stored Properties section on the Properties page of the Swift Programming Language Guide. Note that that link is to pre-release documentation.

提交回复
热议问题