What are variables and constants?
Variables, constants, type inference, tuples and collections in modern Swift. The first post in the Swift Basics series.
This is an updated version of the original post published in 2021. Swift has matured enormously and in 2026 there are conventions and best practices every developer should know from day one. We revisit the fundamentals with the modern Swift used today.
What are variables and constants?
Variables and constants are the names we assign to memory spaces to store values we’ll use throughout our code. In Swift the distinction between them is fundamental and the compiler forces you to be explicit from day one.
Constants with let — the default in modern Swift
In modern Swift the golden rule is: use let whenever you can, use var only when you need to change the value. This isn’t just style — the compiler will warn you if you declare a var you never modify.
let language = "Swift"
let currentYear = 2026
let pi = 3.14159
// Trying to modify a constant is a compile error
// language = "Other" ❌ error: cannot assign to value: 'language' is a 'let' constant
Variables with var — when the value changes
Use var only when the value needs to change during program execution. Common examples: counters, view states, results of dynamic calculations.
var score = 0
score += 10
score += 25
print(score) // 35
var isLoading = false
isLoading = true // ✅ valid because it's a var
Type inference — Swift figures it out
Swift is a statically typed language but with very powerful type inference. In practice you don’t need to write the type explicitly most of the time — the compiler infers it from the initial value. This is the idiomatic style in modern Swift.
// Swift infers the type automatically ✅ (recommended style)
let title = "Hello Swift" // String
let version = 2 // Int
let price = 0.99 // Double
let available = true // Bool
// Explicit annotation — use it when it adds clarity
let identifier: UUID = UUID()
let downloadLimit: Int = 100
An important note: Swift infers decimal literals as Double by default, not Float. In modern Swift Double is the standard type for decimals — it has more precision (64 bits vs 32 bits) and is what most Apple APIs use.
Basic types in Swift
let text: String = "Hello from Swift" // Text strings
let integer: Int = 42 // Whole numbers
let decimal: Double = 3.14159 // Decimals (prefer Double over Float)
let flag: Bool = true // true or false
let character: Character = "A" // A single character (rare in practice)
In day-to-day practice Character is almost never used directly — we normally work with String and manipulate it. Don’t worry too much about that type.
String Interpolation
One of the most used features in Swift is string interpolation with \(). It lets you insert values directly inside a text without concatenating with +.
let product = "Subscription"
let version = 3
let description = "Welcome to \(product) version \(version)"
print(description) // "Welcome to Subscription version 3"
// You can also include expressions
let discount = 0.20
let price = 9.99
print("Final price: \(price * (1 - discount))") // "Final price: 7.992"
Tuples — grouping related values
Tuples let you group multiple values into one. They’re ideal for returning more than one value from a function or representing a simple composite piece of data. In modern Swift they’re often used with named elements for better readability.
// Named tuple — much more readable
let httpResponse = (code: 200, message: "OK")
print(httpResponse.code) // 200
print(httpResponse.message) // "OK"
// You can also destructure it directly
let (code, message) = httpResponse
print(code) // 200
print(message) // "OK"
// Ignore values you don't need with _
let (statusCode, _) = httpResponse
print(statusCode) // 200
Note: For more complex data or data reused across multiple places, prefer using struct over a tuple. Tuples are convenient for quick internal use, not for public APIs.
Collections
Swift has three main collection types: Array, Dictionary and Set. In modern Swift they’re almost always declared with type inference and literals.
Array — ordered list
An array stores values of the same type in order. Elements can repeat and are accessed by index.
// Modern declaration — Swift infers [String]
var colors = ["Red", "Green", "Blue"]
// Add elements
colors.append("Yellow")
// Access by index (0-based)
print(colors[0]) // "Red"
// Iterate (idiomatic Swift style)
for color in colors {
print(color)
}
// Useful in modern Swift
print(colors.count) // number of elements
print(colors.isEmpty) // false
colors.remove(at: 1) // removes "Green"
colors.removeAll() // empties the array
Dictionary — key-value pairs
A dictionary stores key-value pairs with no guaranteed order. Keys must be unique. It’s the equivalent of a HashMap in other languages.
// Swift infers [String: Int]
var scores = ["Player1": 100, "Player2": 95, "Player3": 88]
// Access — returns Optional because the key might not exist
if let points = scores["Player1"] {
print("Points: \(points)") // "Points: 100"
}
// Add or modify
scores["Player4"] = 75
scores["Player1"] = 110
// Delete
scores["Player3"] = nil
// Iterate
for (player, points) in scores {
print("\(player): \(points)")
}
Set — unique unordered values
A Set stores unique values with no order. It’s ideal when you need to guarantee no duplicates or when you need set operations (union, intersection, difference).
// Requires explicit annotation because the literal looks like an Array
var categories: Set<String> = ["Games", "Utilities", "Education"]
categories.insert("Productivity")
categories.remove("Games")
// Duplicates are silently ignored
categories.insert("Utilities") // nothing changes
print(categories.count) // still 3
// Set operations
let group1: Set = [1, 2, 3, 4]
let group2: Set = [3, 4, 5, 6]
print(group1.union(group2)) // {1, 2, 3, 4, 5, 6}
print(group1.intersection(group2)) // {3, 4}
When to use each collection?
- Use Array when order matters or you need to access by position.
- Use Dictionary when you need to look up values by an identifying key.
- Use Set when the uniqueness of elements is most important and order doesn’t matter.
Summary: the golden rules of modern Swift
In the next post in the series we’ll look at basic operators in modern Swift — comparison, logical, range and the nil-coalescing operator you’ll use constantly.