</>
Skip to content
Swift lessons (16/33)

Swift — Closures

Basic closure

let greet = { (name: String) -> String in
    return "Hello, \(name)!"
}
print(greet("Alice")) // Hello, Alice!

Trailing closure

let nums = [3, 1, 4, 1, 5, 9]

// Trailing closure
let sorted = nums.sorted { $0 < $1 }
print(sorted) // [1, 1, 3, 4, 5, 9]

// Multiple trailing closures
UIView.animate(withDuration: 0.3, animations: {
    view.alpha = 0
}, completion: { _ in
    view.removeFromSuperview()
})

Shorthand argument names

let nums = [1, 2, 3, 4, 5]

let doubled = nums.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8, 10]

let sum = nums.reduce(0) { $0 + $1 }
print(sum) // 15

Capturing values

func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}

let counter = makeCounter()
print(counter()) // 1
print(counter()) // 2
print(counter()) // 3

Closures as parameters

func perform(_ operation: (Int, Int) -> Int, on a: Int, _ b: Int) -> Int {
    operation(a, b)
}

print(perform(+, on: 3, 4))    // 7
print(perform(*, on: 3, 4))    // 12
print(perform(-, on: 10, 3))   // 7

@escaping closures

var completionHandlers: [() -> Void] = []

func fetchData(completion: @escaping () -> Void) {
    completionHandlers.append(completion)
    completion()
}

fetchData {
    print("Completed")
}

Mini Practice

Write Swift code that:

  1. Creates a closure and passes it to a function
  2. Uses trailing closure syntax
  3. Demonstrates value capture in a closure
  4. Uses @escaping for deferred execution

Up Next

In the next lesson, you'll learn about Arrays — working with collections in Swift.

Related Topics

Frequently Asked Questions about Closures

What is Closures in Swift?

Closures is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Closures?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Closures.

Why is Closures important in Swift?

Closures is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.