Constants and Variable Declarations
Constants and variables are declarations that bind a value and type to an identifier. Constants are initialized with a value and cannot be reassigned afterwards. Variables are initialized with a value and can be reassigned later. Declarations can be created in any scope, including the global scope.
Constant means that the identifier's association is constant, not the value itself – the value may still be changed if it is mutable.
Constants are declared using the let
keyword. Variables are declared
using the var
keyword.
The keywords are followed by the identifier,
an optional type annotation, an equals sign =
,
and the initial value.
_15// Declare a constant named `a`._15//_15let a = 1_15_15// Invalid: re-assigning to a constant._15//_15a = 2_15_15// Declare a variable named `b`._15//_15var b = 3_15_15// Assign a new value to the variable named `b`._15//_15b = 4
Variables and constants must be initialized.
_10// Invalid: the constant has no initial value._10//_10let a
The names of the variable or constant declarations in each scope must be unique. Declaring another variable or constant with a name that is already declared in the current scope is invalid, regardless of kind or type.
_23// Declare a constant named `a`._23//_23let a = 1_23_23// Invalid: cannot re-declare a constant with name `a`,_23// as it is already used in this scope._23//_23let a = 2_23_23// Declare a variable named `b`._23//_23var b = 3_23_23// Invalid: cannot re-declare a variable with name `b`,_23// as it is already used in this scope._23//_23var b = 4_23_23// Invalid: cannot declare a variable with the name `a`,_23// as it is already used in this scope,_23// and it is declared as a constant._23//_23var a = 5
However, variables can be redeclared in sub-scopes.
_13// Declare a constant named `a`._13//_13let a = 1_13_13if true {_13 // Declare a constant with the same name `a`._13 // This is valid because it is in a sub-scope._13 // This variable is not visible to the outer scope._13_13 let a = 2_13}_13_13// `a` is `1`
A variable cannot be used as its own initial value.
_10// Invalid: Use of variable in its own initial value._10let a = a