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

Finding Dependency Cycles in iOS Builds with llbuild UI

Did you know the swift-llbuild project contains a debugging tool called llbuild-ui that can find dependency cycles in your iOS build? To try it: Enable the New Build System (In Xcode it’s under File, Workspace Settings) Build your... Continue →