Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a constant declared with the keyword "let" in Swift? [closed]

Tags:

xcode

swift

the title says it all...Why is a constant declared with the keyword "let" in Swift?

Probably there's a simple answer to this noob question, but I couldn't find it on SO.

EDIT: OK, just to make the question clearer. I know that it needs to be initialized with SOME name, but I thought that there maybe is a deeper meaning to let, a source where it originates? Other stuff like "func" seems very logical to me, so I wonder what the deeper meaning of "let" is.

like image 543
theremin Avatar asked Sep 26 '14 16:09

theremin


1 Answers

Actually in swift there is no concept of constant variable.

A constant is an expression that is resolved at compilation time. For example, in objective C this code:

const NSString *string = [[NSString alloc] init];

results in a compilation error, stating that Initializer element is not a compile-time constant. The reason is that NSString is instantiated at runtime, so it's not a compile time constant.

In swift the closest thing is the immutable variable. The difference may not be evident, but an immutable is not a constant, it's a variable that can be dynamically initialized once and cannot be modified thereafter. So, the compile time evaluation is not needed nor required - although it will frequently happen we use immutables as constants:

let url = "http://www.myurl.com"

let maxValue = 500

let maxIntervalInSeconds = 5 * 60 *60

But immutables can also be initialized with expressions evaluated at runtime:

let url = isDebug ? "http://localhost" : "http://www.myservice.com"

let returnCode: Int = {
    switch(errorCode) {
    case 0: return 0
    default: return 1
    }
}()

The latter example is interesting: using a closure, immediately executed, to initialize an immutable variable (differently from var, immutables don't support deferred initialization, so that's the only way to initialize using a multi line expression)

like image 119
Antonio Avatar answered Oct 18 '22 02:10

Antonio