Swift2: unable to infer closure type in the current context

In Swift 2 this code generates error:

    private lazy var _keyGenerationController = KeyGeneration(nibName: "KeyGeneration", bundle: nil)


Removing lazy or explicitly annotating the type suppresses this error:

    private var _keyGenerationController = KeyGeneration(nibName: "KeyGeneration", bundle: nil)

or:

    private lazy var _keyGenerationController: KeyGeneration = KeyGeneration(nibName: "KeyGeneration", bundle: nil)


What's happening?

Replies

A parsing bug, I think. I ran into it with this code...


final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
   ...
   lazy var preferences: Preferences = Preferences(windowNibName: Preferences.nibName)
   ...
}


If I remove the ": Preferences" thinking that the type will be inferred an error is generated about an unexpected trailing closure.

I just ran into (apparently) the same problem. This compiled OK:


static var speechSynthesizer = NSSpeechSynthesizer (voice: nil)!


but this gave me the error about inferring the type:


static var speechSynthesizer = {
let result = NSSpeechSynthesizer (voice: nil)!
result.delegate = delegate
return result
} ()


and I had to add the type annotation explicitly.

Yep, this is a known bug (and often reported) where type inference isn't working properly with lazy properties. Adding the explicit type annotation is the best way to work around this for now.


-Chris