Kyokook Hwang Kyokook Hwang - 5 months ago 29
Swift Question

Is it normal that lazy var property is initialized twice?

I have met very weird case of using an property with

lazy
keyword. I know this keyword indicates that an initialization of an property is defered until the variable actually being used and just runs once.

However, I found a case running an initialization twice.

class TestLazyViewController: UIViewController {

var name: String = "" {
didSet {
NSLog("name self = \(self)")
testLabel.text = name
}
}

lazy var testLabel: UILabel = {
NSLog("testLabel self = \(self)")
let label = UILabel()
label.text = "hello"
self.view.addSubview(label)
return label
}()

override func viewDidLoad() {
super.viewDidLoad()
testLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
NSLayoutConstraint.activateConstraints([NSLayoutConstraint(item: testLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0)])
NSLayoutConstraint.activateConstraints([NSLayoutConstraint(item: testLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0)])
}

@IBAction func testButton(sender: AnyObject) {
testLabel.text = "world"
}
}


I wrote a view controller for a test. This view controller is presented by another view controller. Then,
name
property is set in
prepareForSegue
of the presenting view controller.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! TestLazyViewController
println("vc = \(vc)")
vc.name = "hello"
}


After running the test, I was able to get the following result.

vc = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.673 testLazy[95577:22267122] name self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.673 testLazy[95577:22267122] testLabel self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>
2015-05-25 00:26:15.674 testLazy[95577:22267122] testLabel self = <testLazy.TestLazyViewController: 0x7fb3d1d16ec0>


As you can see, an initialization code is executed twice. I don't know that it is a bug or a misuse. Is there anybody who lets me know what is wrong?

I also have a guess that it isn't correct what
testLabel
is added to
self.view
in the initialization code. I'm not sure that code is incorrect. It's just only my guess.

UPDATE:

I still don't understand why lazy initialization runs twice. Is it really Swift's bug?

FINAL UPDATE:

@matt has made a excellent explanation for this problem being initialized twice. Although all things come from my incorrect code, I could get valuable knowledge of how
lazy
keyword works. Thanks matt.

Answer

The entire conception of your code is wrong.

  • In prepareForSegue, you must not refer to the interface of the destination view controller, because it has no interface. viewDidLoad has not run yet; the view controller has no view, no outlets, no nothing.

  • Your lazy initializer for the label property should not also add the label to the interface. It should just make the label and return it.

Other things to know:

  • Referring to a view controller's view before it has a view will force that view to load prematurely. Doing this wrong can actually cause the view to load twice, which can have terrible consequences.

  • The only way to ask a view controller whether its view has loaded yet, without forcing the view to load prematurely, is with isViewLoaded().

The correct procedure for what you want to do is:

  • In prepareForSegue, assign the name string to a name property and that's all. It can have an observer, but that observer must not refer to view if we have no view at the time, because doing so will cause the view to load prematurely.

  • In viewDidLoad, then and only then do we have a view, and now you may begin populating the interface. viewDidLoad should create the label, put it into the interface, then pick up the name property, and assign it to the label.


EDIT:

Now, having said all that... What does it have to do with your original question? How does what you are doing wrong here explain what Swift is doing, and is what Swift is doing itself wrong?

To see the answer, simply put a breakpoint on:

lazy var testLabel: UILabel = {
    NSLog("testLabel self = \(self)") // breakpoint here
    // ...

What you'll see is that, because of the way you structured your code, we are getting the value of testLabel twice recursively. Here's the call stack, slightly simplified:

prepareForSegue
name.didset
testLabel.getter -> *
viewDidLoad
testLabel.getter -> *

The testLabel getter refers to the view controller's view, which causes the view controller's view to be loaded, and so its viewDidLoad is called and causes the testLabel getter to be called again.

Note that the getter is not merely being called twice in sequence. It is being called twice recursively: it itself is, in effect, calling itself.

It is this recursion that Swift is failing to defend against. If the setter were merely called twice in succession, the lazy initializer would not have been called the second time. But in your case, it is recursive. So it is true that the second time, the lazy initializer has never been run before. It has been started, but it has never been completed. Thus, Swift is justified in running it now - which happens to mean running it again.

So, in a sense, yes, you've caught Swift with its pants down, but what you had to do in order to make that happen is so outrageous that it can be justifiably called your own fault. It might be Swift's bug, but if so, it is a bug that should simply never be encountered in real life.


EDIT:

In the WWDC 2016 video on Swift and concurrency, Apple is explicit about this. In Swift 1 and 2, and even in Swift 3, lazy instance variables are not atomic, and thus the initializer can run twice if called from two contexts simultaneously — which is exactly what your code does.