Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a specified type of value (such as number 10 or string "Hello. Once set, the constant value cannot be changed, and the variable value can be changed at will.
Declare constants and variables
Constants and variables must be declared before use. let is used to declare constants and var is used to declare variables. The following example shows how to use constants and variables to record the number of user attempts to log on:
let maximumNumberOfLoginAttempts = 10var currentLoginAttempt = 0
The two lines of code can be understood:
"Declare a new constant named maximumNumberOfLoginAttempts and give it a value of 10. Then, declare a variable named currentLoginAttempt and initialize its value to 0 ."
In this example, the maximum number of allowed logon attempts is declared as a constant, because this value will not change. The number of logon attempts is declared as a variable, because this value must be added when logon attempts fail.
You can declare multiple constants or variables in a row, separated by commas:
var x = 0.0, y = 0.0, z = 0.0
Note:
If your code has a value that does not need to be changed, use the let keyword to declare it as a constant. Declare the value to be changed as a variable.
Type Annotation
When declaring a constant or variable, you can add type annotation to indicate the type of the value to be stored in the constant or variable. If you want to add a type annotation, you need to add a colon and space after the constant or variable name, and then add the type name.
This example adds a type annotation to the welcomeMessage variable, indicating that the variable can store values of the String type:
var welcomeMessage: String
The colon in the Declaration represents "Yes... type", so this line of code can be understood:
"Declare a variable of the String type and the name is welcomeMessage ."
"String type" means "any String type value can be stored ."
The welcomeMessage variable can now be set to any string:
welcomeMessage = "Hello"
Note:
Generally, you rarely need to write type annotations. If you assign an initial value when declaring a constant or variable, Swift can infer the type of the constant or variable. For details, refer to type security and type inference. In the preceding example, the welcomeMessage is not assigned an initial value. Therefore, the type of the variable welcomeMessage is specified by a type annotation, rather than the initial value.
Constant and variable naming
You can use any character you like as the constant and variable name, including Unicode characters:
Let π = 3.14159let Hello = "Hello World" let