swift 2.2: failable initializers in lazy properties

Viewed 838

First very appreciate for your help. I just upgraded Xcode yesterday which contains swift 2.2. I've faced a few issues but I fixed them quickly by following the "what's new in swift 2.2" topics from Natashatherobot. But there is one issue I cannot fix. It's about failable initializers of UIFont which was introduced in swift 2.2. Attached is a simple piece of code that will report error in swift 2.2. It might not report the error immediately, until I cleaned the project.

lazy var somelabel: UILabel = {

        let label = UILabel()
        let font = UIFont(name: "somefont", size: 10) ?? UIFont.systemFontOfSize(10) //this line gave me error
        label.font = font
        label.text = "Calculating..."

        return label
    }()

Here is the screenshot of the error

enter image description here

The error is : (name: String, size: CGFloat) -> UIFont' is not convertible to '(name: String, size: CGFloat) -> UIFont?'

I can fix it in two ways:

Method 1: don't put this line: let font = UIFont(name: "somefont", size: 10) ?? UIFont.systemFontOfSize(10) in the 'lazy instantiation' closure. (Put it in computed properties reports no error)

Method 2: instead of using:

 UIFont(name: "somefont", size: 10)

use the below instead( However I don't think this should be the right approach because it makes the initializer more "objc" style):

UIFont.init(name: "somefont", size: 10)

But I still don't understand why it would report me error in the lazy property closure. I will be very appreciated if someone can give me some explanations.

1 Answers
Related