Swift: Swift Variables and Constants
Variables are like labeled boxes you can swap the contents of anytime; constants are like sealed boxes that cannot be changed. This lesson covers the two core ways to store data in Swift.
1. What You'll Learn
- The difference between
var(variables) andlet(constants) - How Swift's type inference automatically identifies data types
- The four basic data types: Int, Double, String, Bool
- How the type safety mechanism prevents code errors
- Converting values between different types
2. A True Story: An E-Commerce Data Analyst
(1) The Pain Point: Mixing Numbers with Text Caused a Crash
Alice is an e-commerce data analyst who processes over 50,000 order records daily. She wrote some code to track monthly sales changes for a product:
var orderCount = "8500"
// Next month, orders grew by 1200
orderCount = orderCount + 1200 // Compilation error!
Swift doesn't allow mixing text and numbers. Alice's code wouldn't compile. It took her 30 minutes to find the root cause—the quotes around "8500" made Swift treat it as text (String) instead of a number (Int).
(2) The Solution: Declaring Variable Types Correctly
Just remove the quotes at declaration, and Swift correctly infers that 8500 is an integer:
// Correct data type definitions
var orderCount = 8500 // Int
var productName = "Headphones" // String
var unitPrice = 49.99 // Double
orderCount = orderCount + 1200
let totalRevenue = Double(orderCount) * unitPrice
print("Product: \(productName)")
print("Monthly sales: \(orderCount), Revenue: $\(totalRevenue)")
Output:
TEXT 📖 Display onlyProduct: Headphones Monthly sales: 9700, Revenue: $485003.0
(3) The Result: Coding Efficiency After Understanding Types
| Dimension | Before | After |
|---|---|---|
| Type-related errors | 5-8 per week | Nearly zero |
| Debugging time per issue | 20-30 minutes | Identified instantly |
| Code readability | String and Int mixed together | Types clearly distinguishable |
| Understanding of types | "When errors happen, just try adding quotes" | "Proactively choose the right type" |
3. Variables and Constants
Swift uses var for variables (values can change) and let for constants (values are fixed after assignment). The choice depends on whether the data needs to change.
graph TB
A[Data Storage] --> B["var Variable"]
A --> C["let Constant"]
B --> D[Value can be modified]
B --> E["var age = 25"]
B --> F["age = 26 ✅"]
C --> G[Value cannot be modified]
C --> H["let name = \"Alice\""]
C --> I["name = \"Bob\" ❌"]
| Feature | var Variable |
let Constant |
|---|---|---|
| Can value change | ✅ Reassignable | ❌ Immutable |
| Use cases | Counters, running totals, temporary data | Fixed config, usernames, math constants |
| Compiler optimization | Normal | May inline optimize |
| Recommendation | Use only when needed | Prefer by default |
(1) Variables — Declared with var
Variables store data that changes during program execution:
// Variable values can be modified at any time
var score = 0
score = 85 // Update value
score = score + 10 // Recalculate based on current value
: Int.
(2) Constants — Declared with let
Once assigned, a constant's value cannot be changed. Using let prevents bugs caused by accidental modification:
// Constants cannot be modified after assignment
let maxLoginAttempts = 5
// maxLoginAttempts = 6 // ❌ Compilation error
let pi = 3.14159
let appName = "MyApp"
let. Whenever data doesn't need to change, declare it with let—your code will be safer and easier to understand.
▶ Example: Managing Shopping Cart Data
// ============================================
// Use variables for cart quantity, constants for product info
// ============================================
// Constants: Fixed information
let productName = "Wireless Headphones"
let unitPrice = 79.99
// Variable: Changing data
var quantity = 1
print("Product: \(productName)")
print("Unit price: $\(unitPrice)")
print("Current quantity: \(quantity)")
// User increased the purchase quantity
quantity = 3
let total = unitPrice * Double(quantity)
print("Buying \(quantity) items, Total: $\(total)")
Output:
TEXT 📖 Display onlyProduct: Wireless Headphones Unit price: $79.99 Current quantity: 1 Buying 3 items, Total: $239.97
4. Basic Data Types
Swift provides four commonly used basic data types, each storing a specific form of data. Once a variable or constant's type is determined, it cannot store data of a different type.
graph TB
A[Basic Data Types] --> B["Int Integer"]
A --> C["Double Floating Point"]
A --> D["String Text"]
A --> E["Bool Boolean"]
B --> F["42, -10, 0"]
C --> G["3.14, -0.5"]
D --> H["\"Hello\""]
E --> I["true / false"]
| Type | Meaning | Examples | Memory |
|---|---|---|---|
Int |
Integer (positive, negative, zero) | 42, -10, 0 |
8 bytes |
Double |
Floating-point (decimal) | 3.14, -0.5 |
8 bytes |
String |
Text string | "Hello", "Swift" |
Dynamic |
Bool |
Boolean | true, false |
1 byte |
(1) Int — Integers
Int stores whole numbers. On 64-bit devices the range is approximately ±9.2 × 10^18:
let year = 2026
var count = -100
let population: Int = 8_000_000_000 // Underscores improve readability
(2) Double — Floating-Point Numbers
Double stores numbers with decimal points, with at least 15 decimal digits of precision:
let temperature = 36.5
var price = 19.99
let taxRate = 0.08
Int and Double cannot be directly mixed in operations. Explicit type conversion is required.
(3) String — Text
String stores textual data, enclosed in double quotes:
let userName = "Alice"
var message = "Welcome to Swift"
let empty = "" // Empty string
(4) Bool — Boolean
Bool has only two values, true and false, used for conditional logic:
let isLoggedIn = false
var isAvailable = true
let isGreater = 10 > 5 // Comparison automatically produces true
▶ Example: User Info Type Check
// ============================================
// Storing user information with different types
// ============================================
let userName = "Bob" // String
var age = 28 // Int
let height = 1.85 // Double
var isPremiumMember = false // Bool
print("Name: \(userName)")
print("Age: \(age)")
print("Height: \(height) m")
print("Member: \(isPremiumMember)")
// Type safety — the following line will not compile
// age = "twenty-eight" // ❌ Cannot assign String to Int
Output:
TEXT 📖 Display onlyName: Bob Age: 28 Height: 1.85 m Member: false
5. Type Annotations and Type Conversion
Swift is a type-safe language—every variable and constant's type must be determined at compile time. You can let Swift infer the type or specify it manually.
(1) Explicit Type Annotations
Add a colon and the type name after the variable or constant name to explicitly specify the type:
let name: String = "Charlie"
var age: Int = 25
var price: Double = 29.99
let isActive: Bool = true
| Approach | Syntax | When to Use |
|---|---|---|
| Type Inference | let name = "Alice" |
Type is obvious from the value |
| Type Annotation | let name: String = "Alice" |
Clarify type intent, initial value is ambiguous |
| Declare First, Assign Later | var name: String → name = "Alice" |
Can't assign immediately at declaration |
(2) Type Conversion
Different types cannot be directly operated on or assigned—explicit conversion is required:
let apples = 3
let pricePerApple = 0.99
// let total = apples * pricePerApple // ❌ Int and Double cannot multiply directly
let total = Double(apples) * pricePerApple // ✅ Convert Int to Double
| Conversion | Meaning | Example |
|---|---|---|
Int(value) |
Convert to integer (truncates decimals) | Int(3.14) → 3 |
Double(value) |
Convert to floating-point | Double(5) → 5.0 |
String(value) |
Convert to text | String(42) → "42" |
▶ Example: Order Total Calculation
// ============================================
// Calculate order total, demonstrating type conversion
// ============================================
import Foundation
let itemCount = 5 // Int
let unitPrice = 12.99 // Double
let taxPercent = 0.08 // Double
// Int must be converted to Double for arithmetic
let subtotal = Double(itemCount) * unitPrice
let taxAmount = subtotal * taxPercent
let total = subtotal + taxAmount
print("Item count: \(itemCount)")
print("Unit price: $\(unitPrice)")
print("Subtotal: $\(subtotal)")
print("Tax (8%): $\(taxAmount)")
print("Total: $\(total)")
// Convert Double to String for text concatenation
let receipt = "Total: $" + String(format: "%.2f", total)
print(receipt)
Output:
TEXT 📖 Display onlyItem count: 5 Unit price: $12.99 Subtotal: $64.95 Tax (8%): $5.196 Total: $70.146 Total: $70.15
6. Full Example: Order Statistics Summary
// ============================================
// E-commerce order statistics summary
// Demonstrates variables, constants, data types, type conversion
// ============================================
import Foundation
// 1. Constants: Store info and fixed configuration
let storeName = "Swift Gear Shop"
let taxRate = 0.07
// 2. Variables: Mutable order data
var orderCount = 0
var totalRevenue = 0.0
// 3. Process first batch of orders
let price1 = 49.99
let qty1 = 3
orderCount += qty1
let subtotal1 = Double(qty1) * price1
totalRevenue += subtotal1
// 4. Process second batch of orders
let price2 = 129.00
let qty2 = 1
orderCount += qty2
let subtotal2 = Double(qty2) * price2
totalRevenue += subtotal2
// 5. Output statistics report
print("Store: \(storeName)")
print("=== Sales Statistics ===")
print("Items sold: \(orderCount)")
print("Total revenue: $\(totalRevenue)")
print("Estimated tax: $\(totalRevenue * taxRate)")
print("Net revenue: $\(totalRevenue * (1 - taxRate))")
let summary = "Processed " + String(orderCount) + " items today"
print(summary)
Output:
TEXT 📖 Display onlyStore: Swift Gear Shop === Sales Statistics === Items sold: 4 Total revenue: $278.97 Estimated tax: $19.5279 Net revenue: $259.4421 Processed 4 items today
❓ FAQ
\(value) or the String() function for explicit conversion.var score: Int to declare first and assign later, or let value: Double = 5 to force 5 to be a Double instead of an Int.&+ for safely handling special cases.📖 Summary
- Use
varfor variables (values can change) andletfor constants (values cannot change) - Swift determines types through type inference, so you don't always need type annotations
- Four basic data types: Int (whole numbers), Double (decimals), String (text), Bool (true/false)
- Swift is a type-safe language—you cannot mix or implicitly convert between different types
- Type conversion uses the
Type(value)syntax, e.g.Double(3)produces3.0 - Prefer
let, usevaronly when the value needs to change
📝 Exercises
- Beginner: Declare a constant
let city = "New York"and a variablevar population = 8_400_000, then use print to output "New York has 8400000 people". - Intermediate: Define a Double variable storing a Celsius temperature, convert it to Fahrenheit (formula: °F = °C × 9/5 + 32), and output the result in both units.
- Challenge: Write a currency converter program. Use a constant to store the exchange rate (1 USD = 0.92 EUR), a variable to store a dollar amount, then calculate and output the corresponding euro amount. Must use at least three types: Int, Double, and String.