Swift Basics: Variables, Types and Optionals
Harry
· 16 Sep 2026
· 11 views
Log in to track your progress and mark lessons complete.
Sponsored
let and var
Swift has two ways to name a value: let for constants (can't change) and var for variables. Prefer let – it makes your intent clear and your code safer.
let name = "Ada" // constant
var score = 0 // variable
score = 10 // fine
// name = "Grace" // error: name is a constant
Type safety and inference
Every value has a type (Int, Double, String, Bool…). Swift usually infers it, but you can be explicit:
let count: Int = 42
let price = 9.99 // inferred Double
let greeting = "Hello, " + name
Optionals: Swift's safety net
An optional is a value that might be missing, written with a ?. This forces you to handle "no value" instead of crashing on a null. Safely unwrap with if let or guard let:
var middleName: String? = nil // may or may not exist
if let mn = middleName {
print("Middle name is (mn)")
} else {
print("No middle name")
}
Optionals are why Swift apps crash far less than apps in languages that allow silent nulls.
Key points
- Use
letby default;varonly when a value must change. - Swift is strongly typed but infers types for you.
- An optional (
?) may hold a value or benil. - Unwrap optionals with
if let/guard let– never force-unwrap blindly.