I'm converting a project to Swift 2.0 and I keep coming across this error everywhere that I'm using a lazy var. This code works perfectly in 1.2 but breaks in 2.0:
lazy private var placeholderImage = UIImage(named: "theImage")
But, this code generates an 'unexpected trailing closure' error in 2.0.
Following the Xcode's suggestions to fix the error, this is what I come out with:
lazy private var placeholderImage: UIImage = UIImage(named: "theImage")!
This compiles and seems to work, but I don't understand why the change was necessary in the first place.
A lazy var is a property whose initial value is not calculated until the first time it’s called. It’s part of a family of properties in which we have constant properties, computed properties, and mutable properties. A lazy property might be lesser known to beginners in Swift but are actually super valuable once you know when and how to use them.
In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.
Error handling in Swift interoperates with error handling patterns that use the NSError class in Cocoa and Objective-C. For more information about this class, see Handling Cocoa Errors in Swift. In Swift, errors are represented by values of types that conform to the Error protocol.
In Apple developer forum an Apple Staff (ChrisLattner) said:
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.
the issue is also discussed in this Google group
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With