Reminder About Let Initialization

Some Swift language features take a while to sink in and become natural. One such feature that I need to remind myself about is that you do not need to set the value of a let constant at the point you declare it in a function as long as you do it before first use.

From the Swift Programming Language:

When a constant declaration occurs in the context of a function or method, it can be initialized later, as long as it is guaranteed to have a value set before the first time its value is read.

The key point is that you do NOT have to set the constant to a value right away. You only have to make sure to set the value before you use it. This is useful anytime you want to conditionally set the value of a constant.

A Quick Example

When creating constraints I want to use the new iOS 11 safe area layout guides when available or fall back to the old top and bottom layout guides. The layout anchors are constants that we can conditionally set based on the API availability:

let topAnchor: NSLayoutYAxisAnchor
let bottomAnchor: NSLayoutYAxisAnchor

if #available(iOS 11, *) {
  topAnchor = view.safeAreaLayoutGuide.topAnchor
  bottomAnchor = view.safeAreaLayoutGuide.bottomAnchor
} else {
  topAnchor = topLayoutGuide.bottomAnchor
  bottomAnchor = bottomLayoutGuide.topAnchor

// Use topAnchor and bottomAnchor

It is easy to forget this and make topAnchor and bottomAnchor a var when they do not need to be. Note that you must initialize the constant once and only once before you use it. If I remove the else clause from the above code the compiler complains that I am using the constant before I initialized it.

Nothing New

This is nothing new. Apple introduced it back in Swift 1.2 and Xcode 6.3 and I notice that Natasha wrote about Late Initialization of Let two years ago. Still I think it is worth repeating in the hope that it sticks for me and other Swift learners.