sakhunzai
sakhunzai

Reputation: 14500

Declaring a constant in swift

As I read the swift guide it says: The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

I tried in REPL but without any luck:

let aConst;
aConst=23;

So how to declare a constant without setting initial value?

Upvotes: 2

Views: 1710

Answers (4)

user523234
user523234

Reputation: 14834

Another example beside Suthan's:

var someVar: NSString

...

someVar = "Some String"

let someUnknownConstant = someVar

Upvotes: 0

Mick MacCallum
Mick MacCallum

Reputation: 130222

You can't just declare a constant without assigning it some sort of value. The compiler needs to know that the constant will have some sort of value. Consider the following example where a constant "isTablet" is computed based on variables that aren't known until runtime.

let isTablet = {
    if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
        return true
    } else {
        return false
    }
}()

Upvotes: 0

Sulthan
Sulthan

Reputation: 130200

Example

let myConstant = getSomeValueFromMethod()

This is what it means that the value doesn't have to be known at compile time...

Upvotes: 4

Connor
Connor

Reputation: 64684

You can't declare a constant, then assign it at the global scope. If you have to do something like this, use a variable instead. When a constant is declared at global scope, it must be initialized with a value.

Docs

Upvotes: 1

Related Questions