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

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

There is probably a simple answer to this noob question, but I could not find it on SO.

EDIT: Okay, just to make the question clearer. I know that it needs to be initialized with SOME name, but I thought that perhaps there is a deeper meaning, the source, where does it come from? Other things like "func" seem very logical to me, so I wonder if there is a deeper meaning for "let".

+8
xcode swift
source share
1 answer

Actually in fast there is no concept of a constant variable.

A constant is an expression that is allowed at compile time. For example, in lens C, this code:

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

results in a compilation error, indicating that the Initializer element is not a compile-time constant . The reason is that NSString is created at runtime, so it is not a compile-time constant.

Soon the closest thing is a constant variable. The difference may not be obvious, but immutable is not a constant, it is a variable that can be dynamically initialized once and cannot be changed after that. Thus, evaluation of compilation time is not required and is not required - although this often happens, we use immutable constants:

 let url = "http://www.myurl.com" let maxValue = 500 let maxIntervalInSeconds = 5 * 60 *60 

But immutable ones 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 last example is interesting: using the closure immediately executed to initialize an immutable variable (other than var , immutables do not support deferred initialization, so the only way to initialize using a multi-line expression)

+11
source share

All Articles