Swift Constants
Understanding immutable values and constants in Swift
🔒 What are Constants?
Constants in Swift store values that never change once set. Use the 'let' keyword to create constants for data that remains fixed throughout your program's execution.
// Creating constants
let appName = "MyApp"
let version = 1.0
print("\(appName) version \(version)")
Output:
MyApp version 1.0
Constant Characteristics
Immutable
Values cannot be changed
let pi = 3.14159
// pi = 3.14 // Error!
Performance
Optimized by the compiler
let maxUsers = 1000
// Compiler optimizes this
Thread Safe
Safe to use across threads
let apiKey = "abc123"
// Safe in concurrent code
Clear Intent
Shows values won't change
let gravity = 9.81
// Clearly won't change
🔹 Declaring Constants
Constants are declared using the
let
keyword:
// Method 1: Let Swift infer the type
let companyName = "Apple Inc." // String
let foundedYear = 1976 // Int
let stockPrice = 150.25 // Double
// Method 2: Explicitly specify the type
let country: String = "United States"
let employees: Int = 150000
let marketCap: Double = 2500000000000.0
// Method 3: Declare first, assign later (only once!)
let ceoName: String
ceoName = "Tim Cook"
// ceoName = "Someone Else" // This would cause an error!
print("Company: \(companyName)")
print("Founded: \(foundedYear)")
print("Stock Price: $\(stockPrice)")
print("Country: \(country)")
print("Employees: \(employees)")
print("CEO: \(ceoName)")
Output:
Company: Apple Inc.
Founded: 1976
Stock Price: $150.25
Country: United States
Employees: 150000
CEO: Tim Cook
🔹 Constants vs Variables
Understanding when to use constants vs variables:
// Constants (use let) - values that never change
let pi = 3.14159
let appVersion = "2.1.0"
let maxLoginAttempts = 3
let welcomeMessage = "Welcome to our app!"
// Variables (use var) - values that can change
var currentUser = "guest"
var loginAttempts = 0
var isLoggedIn = false
var sessionTime = 0
print("=== App Constants ===")
print("Pi: \(pi)")
print("Version: \(appVersion)")
print("Max attempts: \(maxLoginAttempts)")
print("Message: \(welcomeMessage)")
print("\n=== Current State ===")
print("User: \(currentUser)")
print("Attempts: \(loginAttempts)")
print("Logged in: \(isLoggedIn)")
print("Session: \(sessionTime) minutes")
// Simulate user login
currentUser = "john_doe"
loginAttempts = 1
isLoggedIn = true
sessionTime = 15
print("\n=== After Login ===")
print("User: \(currentUser)")
print("Attempts: \(loginAttempts)")
print("Logged in: \(isLoggedIn)")
print("Session: \(sessionTime) minutes")
Output:
=== App Constants ===
Pi: 3.14159
Version: 2.1.0
Max attempts: 3
Message: Welcome to our app!
=== Current State ===
User: guest
Attempts: 0
Logged in: false
Session: 0 minutes
=== After Login ===
User: john_doe
Attempts: 1
Logged in: true
Session: 15 minutes
🔹 Common Use Cases for Constants
Here are typical scenarios where constants are perfect:
// Configuration values
let serverURL = "https://api.myapp.com"
let apiVersion = "v1"
let timeoutSeconds = 30
// Mathematical constants
let earthRadius = 6371.0 // kilometers
let speedOfLight = 299792458 // meters per second
let goldenRatio = 1.618033988749
// App settings
let defaultLanguage = "en"
let supportEmail = "[email protected]"
let privacyPolicyURL = "https://myapp.com/privacy"
// Color values (in a real app, these might be hex codes)
let primaryColor = "Blue"
let secondaryColor = "Gray"
let errorColor = "Red"
print("=== Server Configuration ===")
print("URL: \(serverURL)/\(apiVersion)")
print("Timeout: \(timeoutSeconds) seconds")
print("\n=== Physical Constants ===")
print("Earth radius: \(earthRadius) km")
print("Speed of light: \(speedOfLight) m/s")
print("Golden ratio: \(goldenRatio)")
print("\n=== App Settings ===")
print("Language: \(defaultLanguage)")
print("Support: \(supportEmail)")
print("Privacy: \(privacyPolicyURL)")
print("\n=== Theme Colors ===")
print("Primary: \(primaryColor)")
print("Secondary: \(secondaryColor)")
print("Error: \(errorColor)")
Output:
=== Server Configuration ===
URL: https://api.myapp.com/v1
Timeout: 30 seconds
=== Physical Constants ===
Earth radius: 6371.0 km
Speed of light: 299792458 m/s
Golden ratio: 1.618033988749
=== App Settings ===
Language: en
Support: [email protected]
Privacy: https://myapp.com/privacy
=== Theme Colors ===
Primary: Blue
Secondary: Gray
Error: Red
🔹 Best Practices
Follow these guidelines when using constants:
✅ When to Use Constants (let):
- Configuration values: API URLs, version numbers
- Mathematical constants: Pi, gravity, speed of light
- Fixed data: User's birth date, app name
- Computed once: Values calculated at startup
✅ When to Use Variables (var):
- User input: Form data, search queries
- Counters: Scores, attempts, iterations
- State: Login status, current page
- Temporary data: Calculations, processing results
// Good practice: Use let by default, var only when needed
let userName = "Alice" // Won't change during session
let maxFileSize = 10485760 // 10MB limit, never changes
var uploadProgress = 0.0 // Will change during upload
var filesUploaded = 0 // Counter that increments
// Computed constants
let welcomeText = "Welcome, \(userName)!"
let fileSizeInMB = Double(maxFileSize) / 1048576.0
print("User: \(userName)")
print("Message: \(welcomeText)")
print("Max file size: \(fileSizeInMB) MB")
print("Progress: \(uploadProgress)%")
print("Files uploaded: \(filesUploaded)")
// Simulate file upload
uploadProgress = 45.5
filesUploaded = 2
print("\nAfter uploading:")
print("Progress: \(uploadProgress)%")
print("Files uploaded: \(filesUploaded)")
Output:
User: Alice
Message: Welcome, Alice!
Max file size: 10.0 MB
Progress: 0.0%
Files uploaded: 0
After uploading:
Progress: 45.5%
Files uploaded: 2