Swift Functions

🧩 Swift Functions – Complete Beginner to Advanced Guide (With Examples & Interview Tips)
Functions in Swift are reusable blocks of code that perform a specific task.
They help write clean, modular, testable, and reusable code and are heavily tested in interviews.
1️⃣ What is a Function in Swift? ⭐
A function:
Groups related code
Can take parameters
Can return values
Can be reused multiple times
2️⃣ Basic Function Syntax ⭐
Example
Output
3️⃣ Function with Parameters ⭐
Output
4️⃣ Function with Return Value ⭐
Output
5️⃣ Multiple Parameters & Argument Labels ⭐⭐
📌 length / width → argument labels
📌 l / w → parameter names
6️⃣ Default Parameter Values ⭐⭐
Output
7️⃣ Variadic Parameters ⭐⭐
Output
8️⃣ Functions Without Argument Labels ⭐⭐
📌 _ removes external label.
9️⃣ In-Out Parameters (inout) ⭐⭐⭐
Allows a function to modify the original variable.
Output
🔟 Returning Multiple Values (Tuple) ⭐⭐
Output
1️⃣1️⃣ Function Types ⭐⭐⭐
Functions are first-class citizens.
1️⃣2️⃣ Nested Functions ⭐⭐
1️⃣3️⃣ Closures vs Functions ⭐⭐⭐
| Feature | Function | Closure |
|---|---|---|
| Name | Required | Optional |
| Capture values | ❌ | ✅ |
| Inline usage | ❌ | ✅ |
| Complexity | Lower | Higher |
📌 Closures are anonymous functions.
1️⃣4️⃣ Common Mistakes ❌
❌ Forgetting return type
❌ Missing argument labels
❌ Not using _ when required
❌ Confusing inout usage
📌 Interview Questions (Swift Functions)
Q1. What is inout?
👉 Allows modifying original variable
Q2. Can Swift functions return multiple values?
👉 Yes, using tuples
Q3. Are functions first-class in Swift?
👉 Yes
Q4. Difference between function & closure?
👉 Closures can capture context
✅ Summary
✔ Functions organize code
✔ Support parameters, defaults, variadic
✔ Can return single or multiple values
✔ inout allows modification
✔ Functions are first-class citizens
✔ Essential for Swift development & interviews
