Variables and Data Types
By the end of this lesson you'll store text, numbers, and true/false values in Swift, choose let or var correctly, and handle missing values safely with optionals — the bedrock of every Swift program.
Learn Variables and Data Types in our free Swift course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick…
Part of the free Swift course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • Declare values with var (mutable) and let (constant) — and why to prefer let
- • Let Swift infer types, or write explicit annotations like : Int
- • Use the core types: Int , Double , String , Bool
- • Build clean text with string interpolation \\(name)
- • Represent "maybe no value" with optionals ( Int? , nil )
- • Unwrap optionals safely with if let and ?? , and know why ! is risky
📊 The Core Data Types
Type
Holds
Example
When to use
Int
Whole numbers
let age = 25
Counts, ages, indexes
Double
Decimal numbers
let h = 1.75
Measurements, money, averages
String
Text
let name = "Al"
Names, messages, input
Bool
true / false
let ok = true
Yes/no decisions
Int?
An Int or nil
var n: Int? = nil
A value that might be missing
Text always uses "double quotes" . A ? after any type (like Int? ) makes it optional — it can also hold nil .
1️⃣ var vs let — Mutable or Constant
Every value you name is either a variable or a constant . Use var when the value will change, and let when it won't. The golden rule in Swift is prefer let : it documents that the value is fixed, prevents accidental changes, and helps the compiler optimise. Read this worked example, run it, then you'll write your own.
2️⃣ Types: Inference vs Annotations
Swift is statically typed — every value has one fixed type the compiler knows in advance. Usually you don't write the type: type inference reads the value and picks it for you. When there's no starting value, or you want a specific type, add an explicit annotation with : Type . Remember that Int and Double never mix automatically — convert on purpose with Double(...) or Int(...) .
Your turn. The program below is almost complete — fill in the three blanks marked ___ using the hints, then run it and check the output.
3️⃣ String Interpolation
String interpolation lets you drop a value straight into text using \\(...) — the backslash, then your value in parentheses. It reads far better than joining pieces with + , and you can even run a small calculation inside the parentheses.
4️⃣ Optionals — Handling Missing Values
Optionals are Swift's standout safety feature. An optional type (written with ? , e.g. Int? ) holds either a value or nil — Swift's word for "nothing here". Because "might be missing" is part of the type, the compiler forces you to deal with the empty case, which eliminates the null-crash bugs that plague other languages. You must unwrap an optional before using it: the safe ways are optional binding ( if let ) and nil-coalescing ( ?? ). Force-unwrapping with ! skips the check and crashes on nil , so use it rarely.
Now you try. Fill in the two blanks to handle values that might be missing — one with ?? , one with if let .
Pro Tips
- 💡 Default to let . Start every value as a constant; only change it to var if the compiler tells you it must change.
- 💡 Avoid ! on real data. Anything that came from a user, a file, or a conversion can be nil — reach for if let or ?? instead.
- 💡 Convert numbers explicitly. Wrap with Double(x) or Int(x) when mixing Int and Double .
- 💡 Name things well. loginCount tells a story; x doesn't.
Common Errors (and the fix)
- "Fatal error: Unexpectedly found nil while unwrapping an Optional value" — you force-unwrapped with ! on something that was nil , which crashes. Use if let or ?? to handle the empty case safely.
- "Cannot assign to value: 'pi' is a 'let' constant" — you tried to change a let . Either keep it constant, or declare it with var if it really needs to change.
- "Binary operator '*' cannot be applied to operands of type 'Int' and 'Double'" — you mixed number types. Convert first: Double(apples) * price .
- "Value of optional type 'Int?' must be unwrapped" — you used an optional directly. Unwrap it first with if let , or provide a default with ?? .
📋 Quick Reference
Task
Code
Result
Constant
let pi = 3.14
can't change
Variable
var n = 0
can change
Annotation
let c: Int = 0
explicit type
Interpolate
"Hi \\(name)"
Hi Sam
Optional
var x: Int? = nil
value or nil
Safe unwrap
if let v = x { … }
runs if not nil
Default
x ?? 0
0 when nil
Convert
Double(myInt)
Int → Double
Frequently Asked Questions
Mini-Challenge: Profile Line
No blanks this time — just a brief and an outline. Build it, run it, and check your output against the example in the comments. This is exactly the kind of small program real apps are made of.
🎉 Lesson Complete!
- ✅ let = constant (prefer this), var = mutable
- ✅ Type inference usually picks the type; add : Int -style annotations when needed
- ✅ Core types: Int , Double , String , Bool — convert numbers with Double(...) / Int(...)
- ✅ Build text cleanly with interpolation \\(value)
- ✅ Optionals ( Int? ) hold a value or nil ; unwrap with if let or ?? , and avoid !
- ✅ Next lesson: Control Flow — make decisions with if and repeat work with loops
Practice quiz
Which keyword makes a value that can change later?
- let
- var
- const
- mut
Answer: var. var declares a mutable variable; let is a constant.
Which type holds whole numbers in Swift?
- Double
- Float
- Int
- Number
Answer: Int. Int stores whole numbers; Double stores decimals.
What does an optional type like Int? hold?
- Only an Int
- Always nil
- Two Ints
- An Int or nil
Answer: An Int or nil. An optional holds either a value or nil.
Which is the SAFEST way to unwrap an optional?
- if let
- Force-unwrap with !
- Ignore it
- Cast it
Answer: if let. if let runs only when a value is present, avoiding crashes.
What does the ?? operator do?
- Compares two optionals
- Supplies a default when the value is nil
- Force-unwraps
- Declares an optional
Answer: Supplies a default when the value is nil. Nil-coalescing ?? provides a fallback when the optional is nil.
Why won't Swift add an Int and a Double automatically?
- It always rounds
- Doubles aren't numbers
- They are different types and Swift never converts implicitly
- Int is read-only
Answer: They are different types and Swift never converts implicitly. Swift requires explicit conversion like Double(myInt) to mix number types.
What does Int("hello") return?
- 0
- An error
- "hello"
- nil
Answer: nil. The failable initialiser returns nil when the text isn't a number.
When is force-unwrapping with ! dangerous?
- It crashes if the optional is nil
- It never compiles
- It is always safe
- Only with strings
Answer: It crashes if the optional is nil. Force-unwrapping a nil optional crashes the program.
How does Swift pick a type when you don't write one?
- It defaults to String
- It asks at runtime
- Type inference from the value
- It uses Any
Answer: Type inference from the value. Type inference reads the assigned value and chooses the type.
Which keyword should you prefer by default?
- var
- mutable
- Either is equal
- let
Answer: let. Prefer let; switch to var only when the value must change.
Continue this course
- Previous: Introduction to Swift
- Next: Control Flow