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.
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
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