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

GCD: Using Dispatch Groups for Fun and Profit

I’m republishing this article here so I can reference it later. I recently needed a way to perform an unknown number of asynchronous http requests and wait until they were all done before proceeding. dispatch_groups are a neat feature of... Continue →