Coding/Learn/swift/swift variables constants and types
Swift Foundational Course
01.Introduction, Safety Philosophy & The Toolchain
02.Constants (let), Variables (var) & Type Inference
03.Strings, String Interpolation & Multiline Literals
04.Operators, Range Types & Nil-Coalescing
05.Control Flow: If, Switch Pattern Matching & Guard Statements
06.Optionals, Optional Binding & Optional Chaining
07.Arrays, Sets & Higher-Order Collection Operations
08.Dictionaries, Default Lookups & Tuples
09.Loops, Defer Execution & Labeled Statements
10.Functions, Argument Labels & In-Out Parameters
11.Closures, Trailing Closures & Shorthand Arguments
12.Enums, Raw Values & Associated Values (Tagged Unions)
13.Error Handling: Throwing Functions, Do-Catch & Try Options
14.Structures (struct), Value Semantics & Mutating Methods
15.Classes, Reference Semantics & Inheritance
16.Automatic Reference Counting (ARC), Weak & Unowned References
17.Properties: Stored, Computed, Observers (didSet) & Lazy
18.Protocols, Protocol Extensions & POP (Protocol-Oriented Programming)
19.Generics, Type Constraints & Associated Types
20.Capstone: Production Async/Await Cache & JSON API Engine
Course Certificate0%

Complete all lessons to earn

LearnConstants (let), Variables (var) & Type Inference
2 / 20 0%
Lesson 02 of 20
8 mins read

Constants (let), Variables (var) & Type Inference

PreviousNext Lesson
In Plain English

Swift strongly encourages immutability. Learn when to use let (immutable constant) versus var (mutable variable), how type inference detects types automatically, explicit type annotations, and core primitives (Int, Double, Float, String, Bool).

The Mental Model

"A constant (let) is like engraving your name in stone—once carved, it can never be altered. A variable (var) is like writing on a whiteboard with a dry-erase marker."

Deep Dive: How It Works

let vs var: Always default to let unless you specifically know the value must change.

Type Inference: Swift automatically determines variable types (e.g. let score = 100 infers Int).

Explicit Type Annotation: var rating: Double = 4.5 specifies the type explicitly when inference is ambiguous.

Type Safety: Swift will not implicitly convert types (you cannot add Int and Double without explicit Double(intVal) conversion).

Syntax Blueprint

let maxRetries = 3 // Immutable
var currentAttempt = 0 // Mutable
let timeout: Double = 15.5

Use let for constants and var for variables, optionally adding : Type annotations.

PointCore Rules to Remember

Point star
Immutability First: Using let makes code safer, faster, and clearer to both the compiler and other developers.
Point star
Strong Static Typing: Once declared, a variable can never hold a value of a different data type.
Point star
No Implicit Coercion: Convert numbers explicitly: Double(intVal) or Int(doubleVal).

Common Beginner Traps & How to Fix Them

Mistake:Trying to mutate a value declared with let (e.g. let count = 0; count += 1).

Why it happens: let constants are read-only after initialization.

How to fix: Change let to var if the value legitimately needs to mutate over time.

Pro Tip: The Swift compiler will give you a warning if you declare a variable with var but never mutate it, reminding you to change it to let.

Live Interactive Example

Hit Run Code to see it live
Type Inference and Explicit Conversion
Swift 5.10 / LLVM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: Double(basePrice) converted Int to Double for multiplication, and status was updated because it was declared with var.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate Circle Area with Constants

  • PointDeclare a constant let radius: Double = 5.0.
  • PointDeclare a constant let pi: Double = 3.14159.
  • PointCalculate let area = pi * radius * radius.
  • PointPrint "Area: " followed by area.
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates