SWIFT

Swift Constants: Syntax, Usage, and Examples

Constants in Swift allow you to define values that do not change once they are set. Using constants improves code readability, prevents accidental modifications, and enhances performance by enabling compiler optimizations.

How to Use Constants in Swift

Swift defines constants using the let keyword. Unlike variables (var), assign a value to a constant at the time of declaration, and do not change it later.

let pi = 3.14159
let appName = "MyApp"
let maxConnections = 10

These constants store a floating-point number, a string, and an integer, respectively. If you try to change pi, Swift will throw a compilation error.

When to Use Constants in Swift

Constants help make your code more predictable and maintainable. Here are some common scenarios where constants improve Swift development.

1. Defining Fixed Values

Use constants when you need values that never change, such as mathematical constants, API keys, or configuration settings.

let maxUsers = 100
let apiBaseUrl = "https://api.example.com"
let timeoutInterval = 30.0

2. Improving Code Readability

Constants give meaningful names to values, making your code easier to understand. Instead of using 0.08 for sales tax, define a constant:

let salesTaxRate = 0.08

3. Preventing Unintended Changes

Since constants cannot be reassigned, they prevent accidental modifications in your code. This is particularly useful in multi-threaded environments where variables might be modified from different parts of the program.

Examples of Constants in Swift

Constants appear in various Swift programming use cases. Here are some examples.

Declaring Constants

Declare constants with basic data types:

let username = "Alice"
let maxRetries = 5
let isFeatureEnabled = true

Constants in Functions

Use constants inside functions to store intermediate values that should not change.

func calculateArea(radius: Double) -> Double {
    let pi = 3.14159
    return pi * radius * radius
}

print(calculateArea(radius: 5)) // Output: 78.53975

Constants in Classes

Define constants within Swift classes for properties that should remain unchanged.

class Car {
    let brand: String

    init(brand: String) {
        self.brand = brand
    }
}

let myCar = Car(brand: "Tesla")
// myCar.brand = "Ford" // This will cause an error

Once a constant is assigned in a class, it cannot be modified.

Constants in Structs

Use constants with Swift structures (struct), especially when defining immutable models.

struct User {
    let id: Int
    let name: String
}

let user = User(id: 1, name: "Alice")
// user.id = 2 // Error: Cannot modify a constant property

Global Constants

Declare global constants outside functions or types to remain accessible throughout the program.

let appVersion = "1.0.0"

Global constants improve consistency and reduce redundancy.

Learn More About Constants in Swift

Swift provides additional features related to constants, including static constants, class constants, and best practices for defining constants.

Constant vs. Variable in Swift

Swift differentiates between variables (var) and constants (let). Use let when the value should not change.

var name = "Alice"
name = "Bob" // Allowed

let appName = "MyApp"
appName = "NewApp" // Error: Cannot assign to a constant

Choosing let whenever possible makes your code safer and easier to debug.

Swift Static Constants

A static constant belongs to the type itself rather than an instance. Use static let to define constants that are shared across all instances of a class or struct.

struct Configuration {
    static let apiUrl = "https://api.example.com"
    static let maxRequests = 100
}

print(Configuration.apiUrl) // Output: "https://api.example.com"

Swift Class Constants

Unlike static constants, class constants allow subclassing. Use class var with static to make a constant overridable in subclasses.

class Animal {
    class var species: String {
        return "Unknown"
    }
}

class Dog: Animal {
    override class var species: String {
        return "Canine"
    }
}

print(Dog.species) // Output: "Canine"

Constants in Protocols

Protocols define required constants using computed properties with get.

protocol Configurable {
    var appName: String { get }
}

struct AppConfig: Configurable {
    let appName = "MyApp"
}

Swift Constants in Enums

Enums hold constant values, making them useful for predefined sets of options.

enum HTTPMethod {
    static let get = "GET"
    static let post = "POST"
}

print(HTTPMethod.get) // Output: "GET"

Best Practices for Swift Constants

  • Use let instead of var whenever possible – This prevents unintended modifications.
  • Group related constants – Organize constants in struct or enum for better readability.
  • Use descriptive names – Avoid generic names like value1 or constantX.
  • Keep constants immutable – Use static let for values that should not change within a type.
  • Avoid magic numbers – Define meaningful constants instead of using raw values directly in the code.

Defining Constants in a Separate File

For large applications, store constants in a separate file to keep your code organized.

struct AppConstants {
    static let apiKey = "123456789"
    static let maxUsers = 1000
}

Now access them throughout the project:

print(AppConstants.apiKey)

Swift constants provide a way to store fixed values that do not change, improving code safety and readability.

Learn to Code in Swift for Free
Start learning now
button icon
To advance beyond this tutorial and learn Swift by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH