Courses/Swift/Functions and Closures

    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, reduce for functional programming
    • • Capture values and understand @escaping closures

    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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    ⚠️
    Forgetting argument labelsgreet("Alice") won't compile if the function is func greet(person: String). You need greet(person: "Alice").
    ⚠️
    Strong reference cycles in closures — Closures capture self strongly by default. Use [weak self] in async closures to avoid memory leaks.
    💡
    Pro Tip: Use trailing closure syntax when the last parameter is a closure: names.sorted { $0 < $1 }.

    📋 Quick Reference — Functions & Closures

    PatternSyntax
    Basic functionfunc name(param: Type) -> Return
    Default valuefunc f(x: Int = 0)
    Variadicfunc f(nums: Int...)
    Closure{ (params) -> Return in body }
    maparr.map { $0 * 2 }
    filterarr.filter { $0 > 5 }
    reducearr.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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service