Chapter 72: Swift Functions

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

A function is a named block of reusable code that:

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

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

  • You tell it what you want (by passing arguments)
  • It does its job
  • It gives you back the answer (or nothing)

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

2. The basic syntax — every form you will actually use

2.1 Simplest function — no parameters, no return

Swift

2.2 Function with one parameter (very common)

Swift

Important rule: When calling a function, you must write the parameter label (name:) unless the label is hidden with _ (more later).

2.3 Function that returns a value

Swift

Modern shorthand (very popular — no return keyword needed when body is single expression):

Swift

Hidden parameter label (using _ — common when label would be redundant):

Swift

3. Functions with multiple parameters — real patterns

3.1 Clear labels (most readable)

Swift

3.2 Some labels hidden (very common style)

Swift

→ person and from are external labels (shown when calling) → name and city are internal labels (used inside the function)

3.3 Default values (very common & powerful)

Swift

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

Example 1 — Format Indian currency (very frequent)

Swift

Example 2 — Validate password (very common in forms)

Swift

Example 3 — Calculate final price with tax & discount (business logic)

Swift

Example 4 — Filter active users (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 implicit return Compile error if missing
Using var for parameters func greet(var name: String) { … } 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 *