为什么文字值没有类型?

Why literal value has no type?

类型推断是Swift的强大属性。这意味着编译器可以从程序员提供的值中推断出文字的类型,不需要显式类型说明。

例如var IntNum = 3;编译器可以推断变量 IntNum 是 Int 类型。在 Xcode 中,如果用户按下键并单击变量名称,这里 IntNum,那么 Xcode 会告诉你它是什么类型。
但是,如果我对字面值 3 执行此操作,Xcode 什么也不会提供。我想,我放在屏幕上的文字值根本就没有类型,只有对象变量和常量的类型是 属性。

我猜是这样,谁能给我解释一下?

干杯 SL

没错。

来自the documentation

Type Safety and Type Inference

Type inference is particularly useful when you declare a constant or variable with an initial value. This is often done by assigning a literal value (or literal) to the constant or variable at the point that you declare it. (A literal value is a value that appears directly in your source code)

...

If you combine integer and floating-point literals in an expression, a type of Double will be inferred from the context:

let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double

The literal value of 3 has no explicit type in and of itself, and so an appropriate output type of Double is inferred from the presence of a floating-point literal as part of the addition.