Declarations of Identifiers
1. Constants
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.
// Declare a constant named a.
let a = 1
a = 2 // Invalid: re-assigning to a constant.
2. Variables
Variables are initialized with a value and can be reassigned later.
Variables are declared using the var keyword.
// Declare a variable named b.
var b = 1
b = 2 // valid: assigning new value.
Points to remember
Declaring another variable or constant with a name that is already declared in the current scope is invalid, regardless of kind or type.
Declaring another variable or constant with a name that is already declared in the current scope is invalid, regardless of kind or type.
variables can be redeclared in sub-scopes.
let a = 1 // Declare a constant named a.
if true {
let a = 2 // Declare a constant with the same name a
// This is valid because it is in a sub-scope.
}
A variable cannot be used as its own initial value.
// Invalid: Use of variable in its own initial value.
let x = x
Type Annotations
When declaring a constant, variable and function parameters , an optional type annotation can be provided, to make it explicit what type the declaration has.
// Bool is the type of booleans.
var isThisAwesome: Bool = true
We will discuss more about different types in the next chapter.