-
Book Overview & Buying
-
Table Of Contents
Learning Swift Second Edition - Second Edition
By :
One feature we have not yet discussed is the concept of lazy properties. Marking a property as lazy allows Swift to wait to initialize it until the first time it is accessed. This can be useful in at least a few important ways.
The most obvious way to use lazy properties is to avoid unnecessary memory usage. Let's look at a very simple example first:
struct MyType {
lazy var largeString = "Some String"
}
let instance = MyType()Even though we created a new instance of MyType in the preceding code, largeString is not set until we try to access it. This is great if we have a large variable that may not be needed on every instance. Until it is accessed, it is not taking up any memory.
We can also take this idea of a lazy property even further using a closure to calculate the value:
class Directory {
lazy var subFolders: [Directory] = {
var loaded = [Directory]()
// Load subfolders into 'loaded...
Change the font size
Change margin width
Change background colour