Lesson 4 • Beginner
Functions and Closures ⚙️
Define reusable functions with argument labels, default values, and multiple return types — then master Swift's powerful closure syntax for functional programming.
What You'll Learn in This Lesson
- • Define functions with argument labels, default values, and variadic parameters
- • Return multiple values using tuples
- • Understand closure syntax and shorthand progression
- • Use
map,filter,reducefor functional programming - • Capture values and understand
@escapingclosures
1️⃣ Functions
Swift functions use the func keyword and have unique features like argument labels (external names for clarity) and parameter names (internal names for implementation). This makes function calls read like English sentences.
Try It: Functions
Parameters, returns, defaults, variadic args, and tuples
// Swift Functions — Parameters, Returns, Labels
console.log("=== Basic Functions ===");
// func greet(name: String) -> String
function greet(name) {
return "Hello, " + name + "! Welcome to Swift.";
}
console.log(greet("Alice"));
console.log(greet("Bob"));
console.log();
// Multiple parameters and return values
console.log("=== Multiple Parameters ===");
function calculateBMI(weight, height) {
let bmi = weight / (height * height);
return Math.round(bmi * 10) / 10;
}
console.log("BMI(70kg
...2️⃣ Closures
Closures are self-contained blocks of functionality that can be passed around and used in your code. Swift's closure syntax is elegantly concise — you can progressively shorten closures from full syntax to single operators like <.
Try It: Closures
Closure syntax, map/filter/reduce, chaining, and capturing
// Swift Closures — Anonymous Functions & Functional Programming
console.log("=== What Are Closures? ===");
console.log("Closures are self-contained blocks of code — like functions without names.");
console.log();
// Basic closure syntax
console.log("=== Closure Syntax ===");
console.log("Swift: { (parameters) -> ReturnType in body }");
console.log();
// Sorting with closures
let names = ["Charlie", "Alice", "Eve", "Bob", "Diana"];
console.log("Original: " + JSON.stringify(names));
// Full c
...3️⃣ Advanced Patterns
Functions in Swift are first-class citizens — they can be stored in variables, passed as arguments, and returned from other functions. Understanding @escaping closures is crucial for async programming.
Try It: Advanced Functions
Higher-order functions, @escaping, and autoclosure
// Advanced Function Patterns
console.log("=== Functions as Parameters ===");
function applyOperation(a, b, operation) {
return operation(a, b);
}
let add = (a, b) => a + b;
let multiply = (a, b) => a * b;
let power = (a, b) => Math.pow(a, b);
console.log("add(5, 3) = " + applyOperation(5, 3, add));
console.log("multiply(5, 3) = " + applyOperation(5, 3, multiply));
console.log("power(5, 3) = " + applyOperation(5, 3, power));
console.log();
// Functions returning functions
console.log("===
...⚠️ Common Mistakes
greet("Alice") won't compile if the function is func greet(person: String). You need greet(person: "Alice").self strongly by default. Use [weak self] in async closures to avoid memory leaks.names.sorted { $0 < $1 }.📋 Quick Reference — Functions & Closures
| Pattern | Syntax |
|---|---|
| Basic function | func name(param: Type) -> Return |
| Default value | func f(x: Int = 0) |
| Variadic | func f(nums: Int...) |
| Closure | { (params) -> Return in body } |
| map | arr.map { $0 * 2 } |
| filter | arr.filter { $0 > 5 } |
| reduce | arr.reduce(0, +) |
🎉 Lesson Complete!
You've mastered functions and closures! Next, learn object-oriented programming with classes, structs, and protocols.
Sign up for free to track which lessons you've completed and get learning reminders.