Lazy property initialization in Swift

后端 未结 9 1123
深忆病人
深忆病人 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 04:59

    What about this:

    class Container {
    
        lazy var entries: [String] = self.newEntries()
    
        func newEntries() -> [String] {
    
            // calculate and return entries
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-18 04:59

    Since the entries property is just an array of the values in entriesByNumber you can do all the loading just in entriesByNumber and just have entries depend on entriesByNumber

    lazy var entriesByNumber: [String : Entry] = {
            var ret: [String : Entry] = [:] 
            for (number, entryDict) in entriesDict
            {
                ret[number] = Entry(dictionary: entryDict, container: self)
            }
            return ret
        }
    
    var entries: [Entry] 
    {
        get { return self.entriesByNumber.values }
    }
    
    0 讨论(0)
  • 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.

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