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 variable in Swift is a named, mutable storage location in memory that holds a value of a specific data type. Declared using the var keyword, variables are subject to Swift’s strict static typing and definite initialization rules, meaning their type cannot change once established, and they must be assigned a value before their first read access.

Declaration and Syntax

Variables are declared using the var keyword followed by an identifier. Swift utilizes a robust type inference engine, allowing the compiler to deduce the type from the initial assignment. Alternatively, explicit type annotation can be used to define the type explicitly.
// Type Inference: The compiler infers 'String'
var inferredVariable = "Compiler determines type"

// Explicit Type Annotation
var annotatedVariable: Int = 42

// Declaration without initialization (requires explicit type)
var deferredInitialization: Double

Type Safety and Mutability

Swift is a statically typed language. Once a variable’s type is established—either via inference or annotation—it cannot be changed to hold a value of a different, non-conforming type. Because variables are declared with var (as opposed to constants declared with let), their stored value can be reassigned at runtime, provided the new value matches the established type signature.
var counter: Int = 0
counter = 1 // Valid reassignment

// counter = "One" // Compile-time error: Cannot assign value of type 'String' to type 'Int'

Definite Initialization

Swift enforces definite initialization, a compiler-level guarantee that a variable will not be read before it is assigned a valid value. This prevents undefined behavior associated with accessing uninitialized memory.
var pendingValue: String
// print(pendingValue) // Compile-time error: Variable used before being initialized

pendingValue = "Initialized"
print(pendingValue) // Valid execution

Memory Allocation and Semantics

The behavior of a variable in memory depends on whether it holds a Value Type (e.g., Int, String, struct, enum) or a Reference Type (e.g., class, actor).
  • Value Types: The variable directly contains the data. Local variables holding value types are typically allocated on the stack. Assigning a value type to a new variable creates a logically isolated copy of the instance. However, for standard library variable-length collections (such as String, Array, Dictionary, and Set), Swift employs a Copy-On-Write (COW) optimization. The initial assignment creates a shallow copy that shares the underlying heap storage; a true deep copy of the memory buffer is only allocated if and when one of the instances is mutated.
  • Reference Types: The variable stores a memory address (pointer) referencing an instance allocated on the heap. Assigning a reference type to a new variable copies the pointer, not the underlying instance, meaning both variables reference the same shared memory location. The underlying heap instance remains intact until it is deallocated by Automatic Reference Counting (ARC).

Stored vs. Computed Variables

Variables in Swift can be categorized by how they handle data storage: Stored Variables: Allocate memory to hold a value directly. These can be global, local, or properties of a type. Computed Variables: Do not allocate memory for direct storage. Instead, they provide a get block to retrieve a value dynamically and an optional set block to mutate other properties indirectly. Computed variables must always be declared with var and an explicit type.
var storedVariable: Int = 10

var computedVariable: Int {
    get {
        return storedVariable * 2
    }
    set(newMultiplier) {
        storedVariable = newMultiplier / 2
    }
}

Property Observers

Stored variables can implement property observers (willSet and didSet) to execute arbitrary code immediately before or after the variable’s memory is mutated. This occurs even if the new value is identical to the current value.
var observedVariable: Int = 0 {
    willSet(incomingValue) {
        // Executes before the value is stored
    }
    didSet(previousValue) {
        // Executes after the new value is stored
    }
}
Master Swift with Deep Grasping Methodology!Learn More