Swift by Example: Constants
Understanding Swift constants with this code example showing immutable value declarations using let keyword, type inference, explicit typing, and how constants behave with collection types like arrays and dictionaries.
Code
// Constant declaration using 'let'
let pi = 3.14159
let maxLoginAttempts = 3
// pi = 3.14 // Error: Cannot assign to value: 'pi' is a 'let' constant
// Constants with explicit type
let greeting: String = "Welcome"
// Arrays and Dictionaries as constants are immutable
let numbers = [1, 2, 3]
// numbers.append(4) // Error
// Best practice: Use 'let' by default, 'var' only when neededExplanation
Constants are declared using the let keyword. Once a constant is assigned a value, it cannot be changed. Swift encourages the use of constants wherever possible to make code safer and clearer. If you know a value won't change, declare it with let.
Like variables, constants support type inference. If you assign a literal value, Swift infers the type. You can also use explicit type annotations. Attempting to modify a constant results in a compile-time error, which helps catch bugs early.
When collection types like Arrays or Dictionaries are assigned to a constant, they become immutable. You cannot add, remove, or modify elements. This is different from reference types (like classes), where a constant reference still allows modifying the object's properties (if the properties themselves are mutable).
Code Breakdown
let creates an immutable constant value.pi = 3.14 would cause a compile error because constants cannot be reassigned.greeting: String shows explicit type annotation with constants.let numbers makes the array immutable, preventing element additions or changes.
