Swift: The rules of being lazy (Xcode 6 Beta 7)

Following on from two earlier posts on the rules of the weak and unowned keywords, this post on the lazy keyword is the final one before I examine the rules of pairing the unowned, weak and lazy keywords in closures.

Rules of being lazy

  1. "You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes." (Apple)
  2. Lazy is only valid for members of a struct or class (i.e. properties)
  3. A  computed property cannot be lazy
  4. A closure stored as a property can be lazy
  5. Methods and variables within methods cannot be lazy
According to the above rules, this is valid:
class LazyFileLoad {
    lazy var instructions = NSString.stringWithContentsOfFile("/tmp/instructions.txt", encoding: NSUTF8StringEncoding, error: nil) // OK   
}
While this is not:
class LazyFileLoad {
    lazy var instruct:NSString {
        return NSString.stringWithContentsOfFile("/tmp/instructions.txt", encoding: NSUTF8StringEncoding, error: nil)
    } // error computed properties can't be lazy  
}
This is because the former is a regular property and the latter is a computed property.

Accessing lazy properties

If you use the former code and place a file in your tmp directory (with the title: instructions.txt) the file will load (in the Simulator) using the following:
var a = LazyFileLoad()
print(a.instructions)
But if your user doesn't need the instructions then you can avoid loading them into memory at all.

When to use lazy

Apple instructs us that: "Lazy properties are useful when the initial value for a property is dependent on outside factors whose values are not known until after an instance’s initialization is complete. Lazy properties are also useful when the initial value for a property requires complex or computationally expensive setup that should not be performed unless or until it is needed."

In a forthcoming blogpost, I will discuss closures using the lazy, weak and unowned keywords.

Endorse on Coderwall

Comments