Swift: Variables & Types
What you will learn
How to declare mutable variables with var and constants with let, Swift's type inference, and type safety.
Swift is type-safe with strong type inference — the compiler knows the type without you writing it in most cases.
var name = "Alice" // String (inferred)
let age = 25 // Int (immutable constant)
var height: Double = 5.6 // explicit type annotation
var isStudent = true // Bool
let vs var
letcreates a constant that cannot change. Use it by default — it makes your intentions clearer.varcreates a mutable variable. Only use it when the value genuinely needs to change.
let maxUsers = 100
// maxUsers = 200 // compile error
var currentUsers = 0
currentUsers += 1 // OK
Common types
| Type | Example | Notes |
|---|---|---|
Int |
42, -3 |
Platform-dependent size (64-bit on modern devices) |
Double |
3.14 |
64-bit floating point (default for decimal literals) |
Float |
3.14f |
32-bit floating point (use f suffix) |
Bool |
true, false |
|
String |
"hello" |
|
Array<Int> / [Int] |
[1, 2, 3] |
Ordered collection |
Dictionary<String, Int> / [String: Int] |
["key": 1] |
Key-value pairs |
Type safety
Swift never implicitly converts between types. You must be explicit:
let x = 42 // Int
let y = 3.14 // Double
// let z = x + y // compile error — can't add Int and Double
let z = Double(x) + y // 45.14 — explicit conversion
Common mistakes
- Using
varwhenletwould work — prefer immutability - Adding an
IntandDoublewithout explicit conversion - Expecting type inference when returning from a function — write the return type for documentation
Quick check below!