Programs need to remember things: a player's name, the number of items in a basket, whether a switch is on. A variable is a named place to keep a value so you can use it later.
Swift has two keywords for this. let creates a constant, a value that can't change once it's set. var creates a variable that can. Swift strongly encourages let: Xcode even warns you when a var is never changed, because constants make code safer and easier to reason about.
Every value in Swift has a type, such as a whole number, a decimal or some text. Usually Swift works the type out for you from the value, which is called type inference. In this lesson you'll create constants and variables, meet the basic types, write types explicitly when it helps, convert between types and group values in tuples.
let and var
let name = "Ada" // constant: can't change
var score = 0 // variable: can change
score = 10
score += 5letvalues must be set once and never reassigned.name = "Grace"is a compile error: "cannot assign to value: 'name' is a 'let' constant".varvalues can be changed as often as you like, but always to a value of the same type.- Use
letby default, and switch tovaronly when the value really needs to change.
Types and type inference
| Type | Holds | Example |
|---|---|---|
Int | Whole numbers | 42 |
Double | Decimal numbers | 3.75 |
Bool | true or false | true |
String | Text | "Swift" |
Character | A single character | "S" (with a type annotation) |
Swift infers the type from the value, so let age = 30 is an Int and let price = 9.99 is a Double. Add a type annotation with a colon when you want to be explicit, or when there's no value yet: var total: Double = 0 makes the 0 a Double, and let initial: Character = "A" makes a Character instead of a String.
Naming rules
- Names can include letters, digits and underscores, and even emoji, but can't start with a digit or contain spaces.
- Use lowerCamelCase:
firstName,totalPrice,isLoggedIn. - Names are case-sensitive:
scoreandScoreare different. - Booleans read best as questions:
isMember,hasTicket,canEdit.
Clear names matter more than short ones. let secondsPerMinute = 60 explains itself, while let s = 60 makes readers guess.
Converting types, and tuples
Swift never converts types automatically, not even Int to Double, which prevents subtle bugs. Convert explicitly:
let count = 3
let price = 2.5
let total = Double(count) * price // 7.5
let whole = Int(9.99) // 9, decimals dropped
let text = String(count) // "3"
let number = Int("42") // Optional(42): might failTurning text into a number might fail, so Int("42") returns an optional that you unwrap safely, as the optionals lesson explains.
A tuple groups a few values together: let point = (x: 3, y: 4), then point.x. Tuples are handy for returning two values from a function.
Declaring a constant now and setting it later
A let doesn't have to get its value on the same line. You can declare it with a type and assign it exactly once later, which is useful when the value depends on a decision:
let isMember = true
let message: String
if isMember {
message = "Welcome back"
} else {
message = "Sign up today"
}
print(message) // Welcome backThe compiler checks every path. If one branch forgets to assign message, or tries to assign it twice, the code won't compile, and reading message before it has a value is also an error. This lets you keep a value constant even when working it out takes a few lines.
Several values on one line, and swapping
You can declare more than one variable in a single statement, separated by commas, and you can pull a tuple apart into separate names:
var a = 1, b = 2
let (x, y) = (3, 4) // x is 3, y is 4
let (width, _) = (5, 6) // _ ignores the second value
(a, b) = (b, a) // swap: a is 2, b is 1Pulling a tuple apart like this is called destructuring. The underscore _ means "I don't need this value", and you'll see it again in loops and functions. Swapping with a tuple needs no temporary variable, because Swift reads both values on the right before assigning either one.
Swift Variables Syntax
Constants and variables
let name = "Ada" // constant, inferred String
var score: Int = 0 // variable, explicit type
score += 10
let total = Double(score) * 1.5
let text = String(score)
let maybe = Int("12") // Int? (optional)
let point = (x: 1, y: 2)
point.xSwift Variables Summary
letcreates a constant;varcreates a variable. Prefer let.- Basic types: Int, Double, Bool, String and Character.
- Swift infers types from values; annotate with
: Typewhen needed. - Types never change and never convert automatically; use Double(), Int() and String().
- Converting text to a number returns an optional because it can fail.
Swift Variables Examples
Each example shows the code, the output it produces and what each part does.
A small profile
let name = "Priya"
let age = 28
let height = 1.68
let isMember = true
var points = 120
points += 30
print(name, age + 1, height, isMember, points)
print(type(of: height))Priya 29 1.68 true 150
DoubleLine-by-line explanation
- Lines 1 to 4Types are inferred: String, Int, Double and Bool.
- Line 5points will change, so it's a var.
- Line 7+= adds to the current value.
- Line 9type(of:) shows the inferred type.
Converting between types
let items = 3
let itemPrice = 12.5
let total = Double(items) * itemPrice
print("Total:", total)
let typed = "25"
if let years = Int(typed) {
print("Months:", years * 12)
}
print(Int(9.99), String(items) + " items")Total: 37.5
Months: 300
9 3 itemsLine-by-line explanation
- Line 3Double(items) converts the Int, so it can be multiplied by a Double.
- Lines 7 to 9Int(typed) might fail, so if let only runs the block when it succeeds.
- Line 10Converting to Int drops the decimals; String() turns a number into text.
Tuples
let product = (name: "Mug", price: 8.5, stock: 12)
print(product.name, product.price)
let (name, price, _) = product
print("\(name) costs £\(price)")
let size = (width: 1920, height: 1080)
print("Pixels:", size.width * size.height)Mug 8.5
Mug costs £8.5
Pixels: 2073600Line-by-line explanation
- Line 1A tuple with named parts.
- Line 4Destructuring copies the parts into separate constants; _ ignores one.
- Line 5\( ) inside a string inserts a value, which the strings lesson explains.
Common Swift Variables Mistakes
Changing a constant
let lives = 3
lives = 2 // error: cannot assign to value: 'lives' is a 'let' constantvar lives = 3
lives = 2Mixing Int and Double
let count = 3
let total = count * 2.5 // error: binary operator '*' cannot be applied to 'Int' and 'Double'let total = Double(count) * 2.5Changing a variable's type
var score = 10
score = "ten" // error: cannot assign value of type 'String' to type 'Int'var score = 10
score = 20Swift Variables in Real Projects
Variables in apps
In a SwiftUI app, constants hold fixed values like spacing and colours, while var properties hold the state that changes as people use the app: the text in a search field, whether a toggle is on, the items in a list. Swift's strict types mean mistakes like adding text to a number are caught while you type, long before an app reaches users.
Swift Variables FAQ
What is the difference between let and var in Swift?
let declares a constant that can be assigned once and never changed; var declares a variable that can be reassigned. Both have a fixed type. Use let unless the value genuinely changes, and Xcode will warn you when a var is never modified.
Does let make an array or dictionary unchangeable?
Yes. Arrays, dictionaries, sets and strings are value types in Swift, so a let array can't have items added, removed or replaced: let list = [1] followed by list.append(2) is a compile error. Declare it with var if you need to change its contents.
When should I write a type annotation in Swift?
Write one when there's no starting value, as in let message: String, or when the inferred type isn't the one you want, as in var total: Double = 0 or let grade: Character = "A". Otherwise let Swift infer the type, which keeps code short.
Why can't I add an Int and a Double in Swift?
Swift never converts number types silently, because hidden conversions can lose precision or hide bugs. Convert one side explicitly: Double(count) * price. Plain number literals are the exception, since 2.5 * 2 lets the literal 2 become a Double.
What does the underscore mean in let (x, _) = point?
The underscore is a placeholder for a value you don't need. In let (x, _) = (3, 4), only x is created and the 4 is thrown away. It avoids an unused-variable warning and tells readers the value was ignored on purpose.
Swift Variables Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the declaration so the value can never change.
maxPlayers = 4
What type does Swift infer for let x = 4.0?
What does this print?
var a = 5
let b = a
a = 9
print(b)
Which line correctly multiplies an Int count by 2.5?
What type does Int("abc") produce?
Swift Variables Quiz
5 questions to check what you learned.
What's the difference between let and var?
- let is for numbers, var for text
- var is faster
- There's none
- let values can't change; var values can
What does
Int(9.99)return?- 9
- 10
- 9.99
- nil
Which naming style does Swift use for variables?
- snake_case
- lowerCamelCase
- UPPERCASE
- kebab-case
How do you read the price from
let item = (name: "Pen", price: 1.2)?- item.price
- item["price"]
- item(price)
- item[1].price
Why doesn't Swift convert Int to Double automatically?
- It's a limitation that will be removed
- Doubles aren't supported
- Explicit conversions prevent hidden mistakes and loss of precision
- Ints are always bigger