The let and var keywords in Swift allow you to declare mutable and immutable variables. This post presents an overview of let and var, and the differences between let and var in Swift:

  1. var in Swift
  2. let in Swift
  3. What is the difference between let and var in Swift?
  4. let and var with Classes in Swift
  5. When to use var instead of let in Swift
  6. When to use let instead of var in Swift

var in Swift

The var keyword in Swift allows you to create a mutable variable. A mutable variable can be set more than once.

// Initialize a mutable variable count to 0
// and increment count to 1
var count = 0
count = count + 1

// Initialize a mutable Array variable numbers with
// values [1, 2] and append 3
var numbers = [1, 2]
numbers.append(3)

// Initialize a mutable variable counter of type 
// Counter and increment the value to 1
struct Counter {
    var value: Int

    mutating func increment() {
        self.value = self.value + 1
    }
}

var counter = Counter(value: 0)
counter.increment()

let in Swift

The let keyword in Swift allows you to create immutable variables. An immutable variable can be initialized only once and acts as a constant.

// Initialize an immutable variable count to 0, 
// count cannot be changed
let countConstant = 0

// Initialize an immutable Array variable numbers with
// values [1, 2], numbers cannot be changed
let numbersConstant = [1, 2]

// Initialize an immutable variable counter of type 
// Counter, counter cannot be incremented
struct Counter {
    var value: Int

    mutating func increment() {
        self.value = self.value + 1
    }
}

let counter = Counter(value: 0)

What is the difference between let and var in Swift?

A var variable can be changed after it is initialized. However, a let variable cannot be changed after it is initialized.

A Swift let variable is similar to a const variable in other languages, meaning attempting to reassign, reinitialize, or mutate a Swift let variable will cause a compiler error:

// Initialize an immutable countConstant 
let countConstant = 0

// Changing countConstant is a compiler error:
// Cannot assign to value: 
// 'countConstant' is a 'let' constant
countConstant = 1

// Initialize an immutable numbersConstant
let numbersConstant = [1, 2]

// Reassigning numbersConstant is a compiler error:
// Cannot assign to value: 
// 'numbersConstant' is a 'let' constant
numbersConstant = []

// Mutating numbersConstant is a compiler error:
// Cannot use mutating member on immutable value: 
// 'numbersConstant' is a 'let' constant
numbersConstant.push(3)

// Define Counter
struct Counter {
    var value: Int

    mutating func increment() {
        self.value = self.value + 1
    }
}

// Initialize an immutable Counter
let counter = Counter(value: 0)

// Attempting to reassign counter is a compiler error:
// Cannot assign to value: 
// 'counter' is a 'let' constant
counter = Counter(value: 1)

// Attempting to mutate counter is a compiler error:
// Cannot use mutating member on immutable value: 
// 'counter' is a 'let' constant
counter.increment()

let and var with Classes in Swift

So far this post has used values and structs to show the differences between let and var. Classes behave differently when using let and var because classes are reference types in Swift:

class Counter {
    var value: Int

    init(value: Int) {
        self.value = value
    }

    func increment() {
        self.value = self.value + 1
    }
}

// Both var and let when used with classes allow
// class variables to be changed
var counter = Counter(value: 0)
counter.increment()

let counterConstant = Counter(value: 0)
counterConstant.increment()

// var variables with a class type can be reassigned
counter = Counter(value: 1)

// Attempting to reassign a let variable with a 
// class type will result in a compiler error:
// Cannot assign to value: 
// 'counterConstant' is a 'let' constant
counterConstant = Counter(value: 1)

When to use var instead of let in Swift

Use var for dynamic state in your apps:

class API {
    // Create a mutable variable to store the last API
    // request time
    static var lastRequestTime: Date?
}

class DisplayCell: UICollectionViewCell {
    // Create a mutable variable that will be 
    // reassigned to a label in a user interface 
    var label: UILabel?
}

func process(tasks: [Task]) -> [Results] {
    // Create a mutable array variable to will 
    // mutate as results are added 
    var results = [Results]()

    for task in tasks {
        results.append(task.perform())
    }

    return results
}

When to use let instead of var in Swift

Use let for constants, configuration, and hyper-parameters:

class API {
    // Create a static constant
    static let rootURL = URL(
        string: "https://api.myapp.com/v1/"
    )
}

class DisplayCell: UICollectionViewCell {   
    // Create a static configuration constant
    private static let animationDuration = 0.5
}

func process(tasks: [Task]) -> [Results] {
    // Configure hyper parameters for this function
    let maxTaskExecutionSeconds = 3.0
    let numberOfThreads = 4

    // perform tasks
}

var vs let in Swift

That’s it! By using var and let variables and constants in Swift you can write code that is easier to debug.