swift: handling unwrapped optional in viewDidLoad

I have actually some troubles handling unwrapped optional constant on UIViewController.

Because UI components exist only after viewDidLoad calls, It seems I can't use the 'let' constant modifier on my constant variables who need GUI dependancy.

Here is an example:

class ViewController: UIViewController {

    @IBOutlet weak var blueSquare: UIView!
    var animator:UIDynamicAnimator!

    required init(coder aDecoder: NSCoder) {
        // If animator was constant, it should be initialized here.
        // But blueSquare is not initialized at this time, so I can't
        // call UIDynamicAnimator(referenceView:  blueSquare)
        super.init(coder: aDecoder)

    override func viewDidLoad() {
        // At this time, the initialisation is ok. But animator is now
        // actually modifiable
        self.animator = UIDynamicAnimator(referenceView:  blueSquare)

As you can see, animator is written as if it can be modifiable. The intend isn't.

My question is: is there any nice pattern who can put 'animator' as constant ? I didn't find any documentation dealing with viewDidLoad and constants with GUI dependency paradigm.


That is why you should leverage optionals.

When you declare:

var animator:UIDynamicAnimator!

You make the compiler believe that animator doesn't have to be initialized before calling init(coder). That's a dangerous game you are playing here. Instead you'd much rather use:

var animator:UIDynamicAnimator?

so using the var before it is initialized is reported as an error. Then you can set it up in viewDidLoad and things are back to where they should be.

You are right about assuming that blueSquare can be used only later in the controller's lifecycle and this has nothing to do with Swift syntax; it is a framework constraint. Therefore you need to have animator declared as a dangling reference till it can be inited to something useful. That's what optional provides to you.

Need Your Help

Using css "active tab" technique on single page

php html css

I'm building a navigation system using jquery scrollto. I have my navigation menu in a separate file (( navigation.php )). It is included in 5 locations on the first page (( 5 different sections w/...

Displaying an inverted pyramid of asterisks

c io

I help with my program. I am required to create a inverted pyramid of stars which rows depends on the number of stars the user keys, but I've done it so it does not give an inverted pyramid, it giv...