Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 'unexpected trailing closure' error with lazy var assignment

Tags:

xcode

ios

swift

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.

like image 338
Derrick Hunt Avatar asked Jul 23 '15 21:07

Derrick Hunt


People also ask

What is a lazy Var in Swift?

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.

How are errors represented in Swift?

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.

What is nserror in Swift?

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.


1 Answers

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

like image 106
Alaeddine Avatar answered Nov 15 '22 08:11

Alaeddine