How does let statement work?

If I have a class property

let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate

Each time appDelegate is accessed, would it return the value at the time it is accessed, or would it return the value the first time it was accessed?

I'm trying to understand whether the property above works the same way as

let appDelegate: AppDelegate? = {
    return UIApplication.shared.delegate as? AppDelegate
}()

The second declaration of the appDelegate property runs the closure the first time the property is accessed and never again. Later references to appDelegate returns the value that was returned the first time the property was accessed.

Answered by Claude31 in 724551022

When you declare:

let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate

It is evaluated once and stored in appDelegate. No change after.

The same for the other one. You force evaluation immediately.

On the other end, a computed var would be evaluated each time it is accessed:

var appDelegate: AppDelegate? {
    UIApplication.shared.delegate as? AppDelegate
}
Accepted Answer

When you declare:

let appDelegate: AppDelegate? = UIApplication.shared.delegate as? AppDelegate

It is evaluated once and stored in appDelegate. No change after.

The same for the other one. You force evaluation immediately.

On the other end, a computed var would be evaluated each time it is accessed:

var appDelegate: AppDelegate? {
    UIApplication.shared.delegate as? AppDelegate
}
How does let statement work?
 
 
Q