Variables and constants of Swift for cats (2)
Constant: let
Let is a keyword used to declare constants. (what is a keyword? I don't want to explain it. public in java, @ at the beginning of oc, var in js, and so on ..)
Constant, that is, the amount that is often used (as you can understand) is like a common male, female, π = 3.14 and so on in life. These cannot be changed. constants in swift cannot be changed. Remember this.
// Constant: let c = 20
If you want to change the constant, an error is returned.
Constant Calculation
Let num1 = 1 // The default Integer type is Intlet num2 = 0.8 // The default decimal type is Doublelet num = num1 + num2
The code above will report an error because swift is a speech with strict type requirements and will not perform implicit conversion in any case.
But what should we do if we have to do this? You only need to follow the same type principle.
Let num1 = 1 // The default Integer type is Intlet num2 = 0.8 // The default decimal type is Double // let num = num1 + num2let num3 = Double (num1) + num2let num4 = num1 + Int (num2)
It should be noted that the conversion of double to int Is not rounded to the nearest decimal point.
Variable var
Variables are declared using var. Can be modified after declaration
var v = 20v = 30
But note that only the same type can be changed ,. In the object-oriented thinking, Initialization is equivalent to being born. After a pig is born, you cannot turn it into a person... You can't change it to anything you can...
Note: we cannot copy the string type to the int type, which means swift is a language with very strict type requirements. (A value will never be automatically converted to another type)
Display definition type, Conversion Type
Definition is to use
Var variable name: TYPE = Value
Let variable name: TYPE = Value
The definition type can be displayed, for example
var a:Double = 3
We can press and hold the keyboard option to create and then click variable a to view its type. At this time, we can see that its type is Double.
, Although we do not do the display type, but swift will automatically export it as a double type
Conversion Type
var a:Double = 3var b = (Int)(a)
, We force convert the type. The initialized B automatically derives the Int type.
Summary:
1: variable var can be modified after Initialization
2: always-on let cannot be modified after Initialization
3: Note: In daily development, let should be the first choice. When it must be modified, var should be used.