Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literals in lazy vars in Swift 2 / XCode 7 [Cannot convert value of type String ...]

Whenever a String literal appears in the declaration of a lazy var I get a compilation error in Swift 2 / XCode 7: Cannot convert value of type String to expected argument type '(_builtinStringLiteral: RawPointer, byteSize: Word, isASCII: Int1)' ...

(I had no problems in Swift 1.2 / XCode 6)

The simplest line that produces this error looks something like this:

lazy var foo = "bar"

But more relevantly (annoyingly), it also happens with initializers that take string arguments:

lazy var viewsLabel = HWLabel(color: COLOR_WHITE, font: ProximaNova("Semibold", 13))
lazy var durationIconView = HWIconView(imageName: "TimeIcon", color: COLOR_WHITE)

These are obviously my own initializers, and I'm noticing Apple SDKs don't seem to have Strings as args in initializers very often. Are Strings in inits bad practice?

What does work is wrapping the declaration in a block.

I might do that for now, or just make them not lazy.

I'm still curious though. Is this an XCode 7 bug?

UPDATE:

Just noticed that what does work is not wrapping the declaration in a closure, but rather specifying the type of the var so that it's not inferred.

So, what does work:

lazy var viewsLabel: HWLabel = HWLabel(color: COLOR_WHITE, font: ProximaNova("Semibold", 13))
lazy var durationIconView: HWIconView = HWIconView(imageName: "TimeIcon", color: COLOR_WHITE)

Why the appearance of a String in a lazy var declaration messes with type inference is beyond me. Still have a hunch it might be an XCode 7 bug.

like image 426
Ian Pearce Avatar asked Sep 18 '15 18:09

Ian Pearce


1 Answers

It's a bug, if you add the type of the var it could compile :

I found the answer here : Swift 2.0 'unexpected trailing closure' error with lazy var assignment

like image 161
Fjohn Avatar answered Oct 02 '22 13:10

Fjohn