Lesson 41Closures

Closure Basics

What is a Closure?

Closures are self-contained blocks of code that can be passed around and used in your code. Think of them as "anonymous functions" or "lambdas"!

Function vs Closure

Function

func add(a: Int, b: Int) -> Int

Named, reusable

Closure

{ (a: Int, b: Int) -> Int in ... }

Inline, anonymous

Closure Syntax

{ (parameters) -> ReturnType in
    statements
}

Why Use Closures?

  • Write inline code without full function definitions
  • Use as callbacks and completion handlers
  • Functional programming (map, filter, reduce)
  • Capture context from surrounding scope
main.swift
// WHAT IS A CLOSURE?
// A closure is a self-contained block of code
// Think of it as a "mini function" you can pass around

// FUNCTION vs CLOSURE
// Function:
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

// Same thing as a closure:
let greetClosure = { (name: String) -> String in
    return "Hello, \(name)!"
}

// Both can be called the same way
print(greet(name: "Alice"))      // Hello, Alice!
print(greetClosure("Alice"))     // Hello, Alice!

// BASIC CLOSURE SYNTAX
// { (parameters) -> ReturnType in
//     statements
// }

// SIMPLE EXAMPLES
let sayHello = {
    print("Hello!")
}
sayHello()  // Hello!

let add = { (a: Int, b: Int) -> Int in
    return a + b
}
print(add(5, 3))  // 8

// CLOSURES ARE FIRST-CLASS CITIZENS
// You can:
// 1. Store them in variables
let multiply = { (a: Int, b: Int) -> Int in a * b }

// 2. Pass them to functions
func calculate(_ a: Int, _ b: Int, operation: (Int, Int) -> Int) -> Int {
    return operation(a, b)
}
print(calculate(4, 5, operation: multiply))  // 20

// 3. Return them from functions
func makeMultiplier(by factor: Int) -> (Int) -> Int {
    return { number in number * factor }
}
let triple = makeMultiplier(by: 3)
print(triple(10))  // 30

// WHY USE CLOSURES?
// - Inline code without defining a full function
// - Callbacks and completion handlers
// - Functional programming (map, filter, reduce)
// - Capturing context from surrounding scope

Try It Yourself!

Create a closure that takes two strings and returns them combined with a space. Store it in a variable and call it!