Search code examples
iosconstantsswiftlet

let declarations require an initializer expression


I'm reading The Swift Programming Language, in the Simple Values section

“Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once”

So I think I can do this

let aConstant:Int
aConstant = 5

But I get let declarations require an initializer expression !!

Why is that ? What does they mean by "The value of a constant doesn’t need to be known at compile time" ?


Solution

  • From the Swift Language Reference:

    When a constant is declared at global scope, it must be initialized with a value.

    You can only defer initialization of a constant in classes/structs, where you can choose to initialize it in the initializer of the class/struct.

    The meaning of "The value of a constant doesn’t need to be known at compile time" refers to the value of the constant. In C/Objective-C a global constant needs to be assigned a value that can be computed by the compiler (usually a literal like 10 or @"Hello"). The following would not be allowed in Objective-C:

    static const int foo = 10; // OK
    static const int bar = calculate_bar(); // Error: Initializer element is not a compile-time constant
    

    In Swift you don't have this restriction:

    let foo = 10 // OK
    let bar = calculateBar(); // OK
    

    Edit:

    The following statement in the original answer is not correct:

    You can only defer initialization of a constant in classes/structs, where you can choose to initialize it in the initializer of the class/struct.

    The only place where you cannot defer is in global scope (i.e. top level let expressions). While it's true that you can defer initialization in a class/struct, that's not the only place. The following is also legal for example:

    func foo() {
        let bar: Int
        bar = 1 
    }