Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A constant in Swift is an immutable identifier bound to a specific value or memory address. Declared using the let keyword, a constant guarantees that its assigned value cannot be reassigned once initialized within its defining scope.

Syntax and Declaration

Constants can be declared with explicit type annotations or rely on the Swift compiler’s type inference.
// Type inference
let maximumConnections = 50 

// Explicit type annotation
let environmentName: String = "Production"

Initialization Rules

A constant does not need to be assigned a value immediately upon declaration, but it must be initialized exactly once before its first read access. The Swift compiler enforces definite initialization.
let networkSuccess = true
let responseCode: Int

// Deferred initialization based on control flow
if networkSuccess {
    responseCode = 200
} else {
    responseCode = 404
}

// The compiler guarantees responseCode is initialized before this point
print(responseCode) 

Immutability Mechanics: Value vs. Reference Semantics

The behavior of a constant depends strictly on whether the assigned type is a value type or a reference type. Value Types (Structs, Enums, Tuples) When a constant holds a value type, the immutability is deep. The instance itself and all of its properties become immutable, regardless of whether the internal properties were declared with var.
struct Point {
    var x: Int
    var y: Int
}

let origin = Point(x: 0, y: 0)
// origin.x = 10 // Compiler Error: Cannot assign to property: 'origin' is a 'let' constant
Reference Types (Classes, Actors) When a constant holds a reference type, the immutability is shallow. The constant strictly protects the reference (the memory address pointing to the instance). You cannot reassign the constant to point to a different instance, but you can mutate the underlying instance’s variable properties.
class Session {
    var isActive: Bool = false
}

let currentSession = Session()

// Allowed: Mutating a property of the referenced instance
currentSession.isActive = true 

// Compiler Error: Cannot assign to value: 'currentSession' is a 'let' constant
// currentSession = Session() 

Evaluation Time

Unlike constants in languages like C or C++ (e.g., #define or constexpr), Swift constants declared with let are not restricted to compile-time evaluation. They are evaluated at run-time, meaning a constant can be initialized with the result of a function call or a dynamically calculated expression.
import Foundation

// Run-time evaluation
let currentTimestamp = Date().timeIntervalSince1970
Master Swift with Deep Grasping Methodology!Learn More