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


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:

SWIFT
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:

SWIFT
// 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 only
Product: 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.

100%
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:

SWIFT
// Variable values can be modified at any time
var score = 0
score = 85           // Update value
score = score + 10   // Recalculate based on current value
💡 Tip: When you assign an initial value at declaration, Swift automatically infers the type—you don't need to write : Int.

(2) Constants — Declared with let

Once assigned, a constant's value cannot be changed. Using let prevents bugs caused by accidental modification:

SWIFT
// Constants cannot be modified after assignment
let maxLoginAttempts = 5
// maxLoginAttempts = 6  // ❌ Compilation error
let pi = 3.14159
let appName = "MyApp"
💡 Tip: Apple's official style guide recommends preferring 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

SWIFT
// ============================================
// 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 only
Product: 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.

100%
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:

SWIFT
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:

SWIFT
let temperature = 36.5
var price = 19.99
let taxRate = 0.08
⚠️ Note: 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:

SWIFT
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:

SWIFT
let isLoggedIn = false
var isAvailable = true
let isGreater = 10 > 5  // Comparison automatically produces true

▶ Example: User Info Type Check

SWIFT
// ============================================
// 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 only
Name: 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:

SWIFT
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: Stringname = "Alice" Can't assign immediately at declaration

(2) Type Conversion

Different types cannot be directly operated on or assigned—explicit conversion is required:

SWIFT
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

SWIFT
// ============================================
// 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 only
Item 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

SWIFT
// ============================================
// 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 only
Store: 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

Q Is there a performance difference between let and var?
A The compiler can apply more optimizations to let constants (such as inline substitution), giving it a slight performance edge over var. However, in day-to-day development the difference is negligible—prioritize semantic correctness.
Q Why can't String and Int be directly concatenated?
A Because String and Int are entirely different data types. Swift is a type-safe language and does not allow implicit type conversion. Use string interpolation \(value) or the String() function for explicit conversion.
Q When must I write a type annotation?
A Three cases: no initial value at declaration, the initial value may be ambiguous, or you want to be explicit about the type. For example, 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.
Q What is the maximum Int value? What happens on overflow?
A On 64-bit devices, the Int range is approximately ±9.2 × 10^18. Overflow in debug mode will crash with an error, but Swift also provides overflow operators like &+ for safely handling special cases.

📖 Summary


📝 Exercises

  1. Beginner: Declare a constant let city = "New York" and a variable var population = 8_400_000, then use print to output "New York has 8400000 people".
  2. 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.
  3. 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏