Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sometimes swift static variable is initialized incorrectly when compile for optimize for speed

Tags:

swift

I recently run into a problem that sometimes swift static variables are initialized incorrectly. This issue could be reproduced when compile for speed optimization(which is the default optimize level for release model in Xcode). See the codes below:

class MainView: UIView {
    static let someValue: Int = {
        print("some value init")
        return 1
    }()
}

class ViewController: UIViewController {
    var falseValue = false
    var falseValue2 = false
    override func viewWillAppear(_ animated: Bool) {
        if falseValue {
            print(MainView.someValue)
        }
        if falseValue2 {
            print(MainView.someValue)
        }
    }
}

For the code above, the MainView.someValue should not be initialized, but when compile in release model or optimize for speed(-o), the some value init will be printed, which means the someValue has been initialized. But none of the print in if statement is executed.

Why the compile do this optimization? And this will cause some logic error when someValue's init block do some complex work.

like image 946
NewSelf Avatar asked Sep 19 '19 14:09

NewSelf


1 Answers

This is a bug reported as SR-11494. Stored type properties are supposed to be lazily initialized on their first access. As per the Documentation

However, in this case, when compiled with the optimization flag the stored Type property's initialization is called at compile-time.

Bug Update (12/08/2020):

This issue has been fixed in Swift 5.3

like image 81
byaruhaf Avatar answered Oct 10 '22 04:10

byaruhaf