Let It Go: Late Initialization of Let in Swift

One of the BIG improvements that came in Swift 1.2 was the ability to initialize let a little bit later. According to the Swift blog:

let constants are now more powerful and consistent — The new rule is that a let constant must be initialized before use (like a var), and that it may only be initialized, not reassigned or mutated after initialization.

This enables patterns like:

I was of course aware of this change, yet I haven’t fully internalized it. I’m way too into my habit of using vars in cases like the one mentioned above!

This week, @allonsykraken pointed out at least one common use-case for this in my code. Creating a cell in a table view of course!

So glad I get to use more lets instead of vars!!! Going to have to keep that in mind as I rebuild my var habit.

And of course, the moment you’ve all been waiting for….

You’re welcome!

Enjoy the article? Join over 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • Perluete

    Let is can also be used for all UI components added programmatically.

  • Late let initialization is a nice concept. I Also used vars before this came to Swift 1.2 and I found “late lets” very useful.

    Don’t know if this is just because you wanted to visualize usage of the “late let” but this initialization process could be simplified a bit by using closure to calculate a cell identifier.

    Okay, when writing this I am almost sure you did it because of necessity to visualize the feature but here is how this code could be improved: https://gist.github.com/tomkowz/92762762c34dec2aad89


    • Yes, I simplified this for the example. In real life, I actually have a function to configure and return each cell, which is then assigned to the main cell. I put the cellIdentifier function in the enum.

  • Great Post Natasha :-). I was curious how this *really* works at the compiler level, it’s pretty interesting. The concept is called definitive initialization, I wrote about it here: https://medium.com/the-traveled-ios-developers-guide/on-definitive-initialization-54284ef5c96f

    • Thanks for digging into it and providing the real name for it. Great post!

  • why don’t use “return” in conditions instead of late variable initialization?

    • This was a simplified example. Most of the time, you have to do some configuration to the cell, and there might be commonalities across cells, etc.

  • I like to put this kind of constant initializations inside a closure. In this way it is more clear that the code belongs to that variable initialization and makes it more readable.

    let x : SomeThing = {
    if condition {
    return foo()
    } else {
    return bar()

  • Interesting. I’d forgotten about this. Maybe a nitpick, but I think it’s more readable if you assign the reuseIdentifier instead of the cell:

  • André Claaßen

    Thank you. Great post. let us forget var forever 🙂