Chapter 3: Swift Syntax
Swift Syntax — written as if I’m sitting next to you, explaining slowly, with many small examples, comparisons to other languages you might know (C/C++/Python), common traps, and why Swift does things a certain way.
We will cover the most important syntax patterns you will see in almost every Swift file.
1. Variables & Constants – The foundation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Immutable (cannot be changed) – use this MOST of the time let maximumAttempts = 5 let apiKey = "sk-abc123xyz" let isProduction = true // Mutable (can be changed) var score = 0 var username = "guest123" var temperature = 28.7 score += 10 username = "player_789" temperature -= 2.3 |
Important style rule in modern Swift (2024–2026):
- Default = let
- Use varonly when you are sure the value will actually change
Very common beginner mistake:
|
0 1 2 3 4 5 6 7 |
var name = "Rahul" // ← wrong if you never reassign it! var email = "rahul@xyz.com" // ← wrong if never changed |
Correct:
|
0 1 2 3 4 5 6 7 |
let name = "Rahul" let email = "rahul@xyz.com" |
2. Type annotation vs type inference
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Type inference (preferred in 99% of cases) let age = 27 // Swift knows it's Int let height = 1.74 // Double let isActive = true // Bool let title = "Swift Syntax" // String // Explicit type annotation (use when it improves clarity) let maxFileSize: Int64 = 5_000_000_000 let pi: Double = 3.141592653589793 let statusCode: UInt16 = 200 let userID: UUID = UUID() |
When to write types explicitly:
- When the inferred type is surprising
- Working with very large / small numbers (Int64, UInt32, etc.)
- Interacting with C / Objective-C APIs
- Making function signatures clearer
3. String syntax – very flexible
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Normal string let name = "Ananya" // String interpolation (very common) let greeting = "Hello, \(name)!" // Multi-line string (very clean) let license = """ MIT License Copyright (c) 2025 Your Name Permission is hereby granted, free of charge... """ // Raw string (ignores escapes – useful for regex, paths, JSON) let regexPattern = #"\d{3}-\d{3}-\d{4}"# let windowsPath = #"C:\Users\Public\Documents"# |
Common operations:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let text = "Swift is expressive" text.count // Int text.isEmpty // Bool text.uppercased() text.lowercased() text.hasPrefix("Swift") text.hasSuffix("ive") text.contains("press") |
4. Numbers – literals & separators
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let smallInt = 42 let bigInt = 1_000_000_000 // underscore = readable separator let veryBig = 1_234_567_890_123 let hex = 0xFF // 255 let binary = 0b101010 // 42 let octal = 0o777 // 511 let scientific = 1.23e-4 // 0.000123 let hexFloat = 0x1.8p3 // 12.0 (1.5 × 2³) |
5. Tuples – lightweight mini-structures
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let coordinates = (3, 4) let person = ("Amit", 28, true) let (x, y) = coordinates print(x, y) // 3 4 let (name, age, isStudent) = person // Named tuples (very common in function returns) let result = (status: 200, message: "OK") print(result.status) // 200 print(result.message) // "OK" |
6. Optionals – the syntax that defines Swift
|
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 33 |
// Declaration var name: String? = "Priya" var age: Int? = nil // Most common safe unwrapping patterns // Pattern 1 – if let (classic & very common) if let n = name { print("Name: \(n)") } // Pattern 2 – modern short syntax (very popular 2023+) if let name { print("Hello \(name)") } // Pattern 3 – nil coalescing let displayName = name ?? "Guest" // Pattern 4 – guard (early exit – very clean) guard let age else { print("Age is required") return } print("You are \(age) years old") // Pattern 5 – optional chaining let length = user?.profile?.bio?.count |
Never do this (very dangerous):
|
0 1 2 3 4 5 6 |
let forced = name! // crashes if nil – avoid unless 100% sure |
7. Arrays – syntax variations
|
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 |
// Creation var colors = ["red", "green", "blue"] let numbers: [Int] = [1, 2, 3, 4] // Empty var names: [String] = [] var scores = [Double]() // Append / insert / remove colors.append("yellow") colors += ["purple", "orange"] colors.insert("black", at: 0) colors.remove(at: 2) colors.removeLast() // Access colors[0] // first colors.last // optional last element colors.isEmpty colors.count |
8. Dictionaries – key-value syntax
|
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 |
var scores = [ "Ananya": 92, "Rahul": 85, "Priya": 98 ] // Add / update scores["Vikram"] = 76 scores["Rahul"] = 88 // Remove scores["Vikram"] = nil // Safe access if let s = scores["Ananya"] { print("Score: \(s)") } // Default value let points = scores["Unknown"] ?? 0 // Loop for (name, score) in scores { print("\(name): \(score)") } |
9. Control flow – if, guard, switch
|
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// if – else if – else let temp = 33 if temp >= 35 { print("Extreme heat") } else if temp >= 28 { print("Hot") } else { print("Comfortable") } // guard – early exit (very clean) func processUser(age: Int?) { guard let age else { print("Age missing") return } guard age >= 18 else { print("Too young") return } print("Welcome!") } // switch – very powerful let direction = "N" switch direction { case "N", "North": print("↑") case "S", "South": print("↓") case "E", "East": print("→") case "W", "West": print("←") default: print("Unknown") } // Range matching (very common) let code = 404 switch code { case 200..<300: print("Success") case 400..<500: print("Client error") case 500...: print("Server error") default: print("Weird") } |
10. Functions – basic syntax patterns
|
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 |
// Simple func sayHello() { print("Namaste!") } // With parameters (external + internal names) func greet(person name: String, age years: Int) { print("Hello \(name), you are \(years) years old.") } greet(person: "Meera", age: 24) // Default values func connect(to host: String = "api.example.com", port: Int = 443) { print("Connecting to \(host):\(port)") } // Returning value func square(_ number: Int) -> Int { return number * number } // Multiple return values (tuple) func minMax(numbers: [Int]) -> (min: Int, max: Int)? { guard !numbers.isEmpty else { return nil } return (numbers.min()!, numbers.max()!) } |
Quick Summary Table – Most Important Syntax Patterns
| What | Syntax Example | Most common style in 2025–2026 |
|---|---|---|
| Constant | let count = 10 | Always prefer let |
| Optional | var email: String? | if let, guard let, ?? |
| String interpolation | “Hello \(name)” | Almost always used |
| Array | var items: [String] = [] | append, for-in |
| Dictionary | [String: Int] | subscript + ?? |
| Switch with ranges | case 200..<300: | Very common for status codes |
| Guard | guard let x else { return } | Preferred for early exits |
| Function labels | greet(person name: String) | Clear external names |
Would you like to go deeper into any of these areas next?
- Enums (very powerful in Swift)
- Struct vs Class (when to use which)
- Closures (very important syntax)
- Async/await syntax patterns
- Property wrappers (@State, @Published, @ObservedObject…)
- Or start building a small complete example program
Tell me what feels most useful or interesting to you right now 😊
