How would you implement the following pattern in Swift?
The Container
class is initialized with a JSON array that contains dictionaries. These dictionar
What about this:
class Container {
lazy var entries: [String] = self.newEntries()
func newEntries() -> [String] {
// calculate and return entries
}
}
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 }
}
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:
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.