More on Lazy Initialization in Swift

@ColinEberhardt wrote a great post titled Swift Initialization and the Pain of Optionals. In the post, Colin mentions not being able to pass parameters to initializers when assigning to a variable marked lazy. The workaround he found was to use a closure. Colin gave two examples:

lazy private var animator = UIDynamicAnimator(referenceView: self.view)

which did not compile and:

lazy private var animator: UIDynamicAnimator = {
    return UIDynamicAnimator(referenceView: self.view)

which did compile. @schukin noticed that Colin also added an explicit type to the variable declaration in the second example. Doing the same with Colin’s first example fixes the compilation error:

lazy private var animator: UIDynamicAnimator = UIDynamicAnimator(referenceView: self.view)

So it turns out that you can reference variables regardless of whether or not you use a closure. The important thing is providing a type if you pass parameters to an initializer being assigned to a variable marked lazy. It seems compiler can infer the type being assigned when you do not pass parameters but it cannot infer the type when you pass parameters.

This brings up two questions:

  1. Why is the compiler not able to infer the type returned by an object’s initializer when parameters are passed?
  2. Does using a closure provide utility other than being able to do more complex lazy initialization?

Now read this

Improving Swift Debug Build Times

It’s well known that enabling Whole Module Optimization greatly reduces Swift build times, but did you know it’s possible to do this for debug builds without breaking the debugger? I didn’t. Normally, one sets SWIFT_OPTIMIZATION_LEVEL to... Continue →