Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" ?

like image 714
onmyway133 Avatar asked Jun 09 '14 16:06

onmyway133


2 Answers

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 
}
like image 135
Alfonso Avatar answered Oct 05 '22 23:10

Alfonso


A constant does not need to be known at compile, but it must have a value after initialization:

class MyClass: NSObject {
    let aConstant: Integer; // no value

    init()  {
        aConstant = 4; // must have a value before calling super
        super.init();
    }
}

This allows you to set the constant to a value after it is declared and potentially unknown at compile time.

like image 30
Firo Avatar answered Oct 05 '22 22:10

Firo