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.

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories