Chapter 71: Functions

1. What is a function? (the most honest explanation)

A function is a named piece of reusable code that:

  • takes zero or more inputs (parameters)
  • does some work
  • optionally returns a result

Think of a function as a small worker inside your program:

  • You give it instructions (parameters)
  • It does its job
  • It hands back a result (or nothing)

Functions are the building blocks of every non-trivial program.

2. The basic syntax — all the common forms

Form 1 – Simplest function (no parameters, no return)

Swift

Form 2 – With parameters (most common)

Swift

Important: In Swift, when you call the function, you must label the arguments (unless you use _ — more later).

Form 3 – With return value

Swift

Shorthand return (very common & clean):

Swift

Form 4 – Multiple parameters + labels

Swift

You can make some labels external and some internal:

Swift

3. Real-life examples — functions you will actually write

Example 1 – Format currency (very common)

Swift

Example 2 – Validate email (very common in forms)

Swift

Example 3 – Calculate discount (business logic)

Swift

Example 4 – Filter active users (very common in social / admin apps)

Swift

5. Very Common Beginner Mistakes & Correct Habits

Mistake Wrong / Risky code Correct / Better habit Why?
Forgetting to return value func add(a: Int, b: Int) -> Int { a + b } return a + b or use implicit return Compile error if missing
Using var for parameters unnecessarily func greet(name: String) { name = “Hello” + name } Parameters are let by default — good! Prevents accidental mutation
Force-unwrapping in functions func getName(user: User?) -> String { user!.name } guard let user else { return “Guest” } Safer, better error handling
Too many parameters func createUser(name, age, city, email, phone, …) Use struct / DTO instead More readable, easier to extend
Side-effects in pure functions func calculateTotal(price: Double) -> Double { print(“Calculating…”); return price * 1.18 } Keep functions pure when possible Easier to test, predict

6. Quick Reference – Function patterns you will use most

Goal Most idiomatic style Notes / Tip
Simple action (no return) func log(message: String) { print(message) } Side-effect functions
Pure calculation func add(_ a: Int, _ b: Int) -> Int { a + b } Implicit return, no return keyword
Optional return func findUser(id: Int) -> User? { … } Return nil when not found
Multiple outputs func divide(_ a: Double, by b: Double) -> (quotient: Double, remainder: Double) Use tuple or custom struct
Default parameters func greet(name: String = “Guest”) { … } Very common for optional arguments
Throwing function func loadData() throws -> Data { … } Use try, do-catch when calling

7. Small Practice – Try these

  1. Write a function greetUser(name: String, age: Int) that prints: “Namaste [name]! You are [age] years old.”
  2. Write a function calculateDiscountedPrice(original: Double, discountPercent: Double = 10) -> Double
  3. Write a function isStrongPassword(_ password: String) -> Bool that checks:
    • length ≥ 8
    • has at least one uppercase
    • has at least one number

Paste your code here if you want feedback or want to see even cleaner versions!

What would you like to explore next?

  • Functions with default parameters & variadic parameters (…)
  • Throwing functions (throws, try, do-catch)
  • Function types & closures (very important)
  • Nested functions & higher-order functions
  • Functions in SwiftUI (action closures, view builders)
  • Or move to another topic (optionals, arrays, switch, loops…)

Just tell me — we’ll continue in the same clear, detailed, patient style 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *