Chapter 4: Swift Statements
1. What is a “statement” in Swift?
A statement is any complete instruction that Swift can execute. It usually ends with a semicolon ; — but in Swift you almost never need to write ; at the end (only when you put multiple statements on one line).
Examples of statements:
|
0 1 2 3 4 5 6 7 8 9 |
print("Hello") // expression statement let name = "Priya" // declaration statement return 42 // control statement break // control statement |
2. Most Common Category: Simple Expression Statements
These are the statements you write most often — they evaluate an expression and (usually) do something with the result.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
// Most common print("Namaste!") // calls function score += 10 // assignment + arithmetic names.append("Aarav") // method call isRaining = false // assignment temperature -= 2.5 // compound assignment user?.updateProfile() // optional chaining |
Important note: Even a function call that returns something is a valid statement — you can ignore the return value.
|
0 1 2 3 4 5 6 |
_ = loadUserData() // I call it but I don't use the result |
3. Declaration Statements (let, var, func, struct, enum, class…)
These introduce new names into your code.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Variables and constants let maximumUsers = 100 var currentUsers = 0 // Computed property inside struct/class var fullName: String { return firstName + " " + lastName } // Typealias typealias UserID = Int64 // Function declaration func calculateTax(income: Double) -> Double { return income * 0.18 } // Structure / Class / Enum struct Point { var x: Double var y: Double } |
4. Control Flow Statements – if, guard, switch
These decide which code runs.
4.1 if – else if – else
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
let temperature = 34 if temperature > 38 { print("Heatwave warning!") } else if temperature > 32 { print("Very hot day") } else if temperature > 25 { print("Typical summer") } else { print("Quite pleasant") } |
One-line if (sometimes used):
|
0 1 2 3 4 5 6 |
if isLoggedIn { showDashboard() } |
4.2 guard – very popular in Swift
guard is used for early exit — it makes code much easier to read.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
func processOrder(items: [String]?, address: String?) { guard let items else { print("No items selected") return } guard !items.isEmpty else { print("Cart is empty") return } guard let address, !address.isEmpty else { print("Delivery address required") return } print("Order is valid — proceeding to payment") } |
Key difference:
- if let = keep going deeper (nested)
- guard let = exit early → flatter, cleaner code
4.3 switch – very powerful in Swift
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let grade = "A+" switch grade { case "A", "A+": print("Excellent!") case "B", "B+": print("Good") case "C": print("Average") case "D", "F": print("Needs improvement") default: print("Invalid grade") } |
Advanced switch examples you see often:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// Ranges let statusCode = 404 switch statusCode { case 200..<300: print("Success") case 400..<500: print("Client error") case 500...: print("Server error") default: print("Unknown") } // Matching enums (very common) enum Direction { case north, south, east, west } let heading = Direction.north switch heading { case .north: print("↑") case .south: print("↓") case .east: print("→") case .west: print("←") } |
5. Loop Statements
5.1 for-in loop (most common)
|
0 1 2 3 4 5 6 7 8 9 10 |
let cities = ["Hyderabad", "Bengaluru", "Chennai", "Pune"] for city in cities { print("I love \(city)!") } |
With index:
|
0 1 2 3 4 5 6 7 8 |
for (index, city) in cities.enumerated() { print("\(index + 1). \(city)") } |
5.2 for with range
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
for number in 1...5 { print(number) // 1 2 3 4 5 } for i in 0..<10 { print(i) // 0 to 9 } |
5.3 while & repeat-while
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var count = 0 while count < 5 { print("Count is \(count)") count += 1 } var diceRoll: Int repeat { diceRoll = Int.random(in: 1...6) print("Rolled: \(diceRoll)") } while diceRoll != 6 |
6. Transfer Statements – control flow jumps
These change the normal flow.
| Statement | What it does | Where you use it most |
|---|---|---|
| break | Exit the nearest loop / switch | Loops, switch |
| continue | Skip to next iteration of loop | Loops |
| fallthrough | Continue to next case in switch | Rare, intentional |
| return | Exit function / closure | Functions |
| throw | Throw an error | Throwing functions |
Examples:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
for number in 1...10 { if number == 7 { continue } // skip 7 if number == 9 { break } // stop at 9 print(number) } // fallthrough (rare but useful sometimes) let value = 2 switch value { case 1: print("One") fallthrough case 2: print("Two") default: print("Other") } |
7. do – catch (Error Handling Statements)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
enum NetworkError: Error { case timeout case invalidURL } func fetchData() throws { throw NetworkError.timeout } do { try fetchData() print("Success") } catch NetworkError.timeout { print("Request timed out") } catch { print("Unknown error: \(error)") } |
Modern short version:
|
0 1 2 3 4 5 6 7 8 9 10 |
if let data = try? fetchData() { // success } else { // failed } |
Quick Reference Table – Most Important Statements
| Kind | Statement Example | Most Common Use Case |
|---|---|---|
| Expression | print(“Hi”) | Doing work, calling functions |
| Declaration | let name = “Amit” | Creating variables, functions, types |
| if | if age >= 18 { … } | Simple conditions |
| guard | guard let name else { return } | Early exit / input validation |
| switch | switch status { case 200..<300: … } | Multiple conditions, enums, ranges |
| for-in | for item in array { … } | Iterating collections |
| while / repeat-while | while condition { … } | Unknown number of iterations |
| return | return result | Exit function with value |
| break / continue | if condition { break } | Early exit from loop |
| do-catch | do { try … } catch { … } | Handling errors |
Small Practice – Combine several statements
Try writing this in a playground:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
let temperatures = [28, 34, 41, 19, 25] for (index, temp) in temperatures.enumerated() { print("\(index + 1). Today's temperature: \(temp)°C") guard temp <= 40 else { print(" → Heat alert! Stay hydrated!") continue } switch temp { case ..<20: print(" → It's chilly — wear a jacket") case 20..<30: print(" → Nice weather") case 30...: print(" → Hot day") default: break } } |
Next topic you want to explore deeply?
- More about switch (pattern matching, associated values)
- Closures (very important statement style)
- defer statement (cleanup code)
- throwing functions & do-try-catch in more detail
- async/await statements (modern concurrency)
Just tell me what you want next — we’ll keep going in the same detailed way 😊
