Swift Variables
Swift Variables
Declare constants with let, variables with var, and use type inference or annotations as needed.
Constants and Variables
Declare constants with let and variables with var.
Constants cannot be reassigned.
Example
let constant = 10
var counter = 0
counter += 1
// constant = 12 // Error if uncommented
print(constant, counter)
This example shows that var can change while let cannot.
Swift Type Inference
Swift infers types automatically when possible, but you can also use annotations for clarity.
This example shows that Swift infers types automatically when possible, but you can also use annotations for clarity.
Swift Data Types will be covered in more detail in the Swift Data Types chapter.
Optionals
Use ? to declare values that may be nil.
This example shows an optional that may be nil.