xcode 为什么在 Swift 中用关键字“let”声明了一个常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26063763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 05:42:32  来源:igfitidea点击:

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

xcodeswift

提问by theremin

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

标题说明了一切......为什么在 Swift 中用关键字“let”声明一个常量?

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

这个菜鸟问题可能有一个简单的答案,但我在 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.

编辑:好的,只是为了让问题更清楚。我知道它需要使用 SOME 名称进行初始化,但我认为可能有更深层次的含义,它起源于何处?像“func”这样的其他东西对我来说似乎很合乎逻辑,所以我想知道“let”的深层含义是什么。

采纳答案by Antonio

Actually in swift there is no concept of constant variable.

实际上在 swift 中没有常量变量的概念。

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

常量是在编译时解析的表达式。例如,在目标 C 中,此代码:

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 NSStringis instantiated at runtime, so it's not a compile time constant.

导致编译错误,说明Initializer element is not a compile-time constant. 原因是它NSString是在运行时实例化的,所以它不是编译时常量。

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 dynamicallyinitialized 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:

在 swift 中最接近的是不可变变量。区别可能不明显,但不可变不是常量,它是一个变量,可以动态初始化一次,之后不能修改。因此,不需要也不需要编译时评估——尽管我们经常使用不可变变量作为常量:

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)

后一个例子很有趣:使用一个立即执行的闭包来初始化一个不可变变量(与 不同var,不可变不支持延迟初始化,所以这是使用多行表达式初始化的唯一方法)