Lazy property initialization in Swift

后端 未结 9 1145
深忆病人
深忆病人 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

    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 }
    }
    

提交回复
热议问题