Back to Blog

Swift: Pass a closure to a function

Sandy LaneSandy Lane

Video: Swift: Pass a closure to a function by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Pass a Closure to a Function

In Swift, closures are self-contained blocks of functionality that can be passed around and used in your code. This example demonstrates how to define a function that accepts a closure as a parameter and how to call that function with different closures to customize behavior.

Code

func performOperation(on number: Int, using operation: (Int) -> Int) -> Int {
  // Call the closure 'operation' with the input number and return the result
  return operation(number)
}

// Example usage: pass a closure that doubles the input
let doubled = performOperation(on: 5) { num in
  return num * 2
}
print("Doubled: \(doubled)")  // Output: Doubled: 10

// Pass a closure that squares the input
let squared = performOperation(on: 4) { $0 * $0 }
print("Squared: \(squared)")  // Output: Squared: 16

// Pass a closure that adds 10 to the input
let plusTen = performOperation(on: 7) { $0 + 10 }
print("Plus Ten: \(plusTen)")  // Output: Plus Ten: 17

Key Points

  • Closures in Swift can be passed as parameters to functions to customize behavior dynamically.
  • The closure parameter type must be specified in the function signature, including input and output types.
  • Trailing closure syntax allows you to write the closure outside the parentheses for cleaner code.
  • Shorthand argument names like $0 can simplify closure expressions when the context is clear.
  • Passing closures enables reusable and flexible code patterns without duplicating function logic.