Back to Blog

Swift: Add 2 numbers using function and closure

Sandy LaneSandy Lane

Video: Swift: Add 2 numbers using function and closure by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Add 2 Numbers Using Function and Closure

In Swift, you can perform simple arithmetic like adding two numbers by defining a function or using a closure. This example demonstrates both approaches, showing how to create a reusable function and a closure that take two integers and return their sum.

Code

// Function to add two numbers
func addNumbers(a: Int, b: Int) -> Int {
  return a + b
}

let sumFunction = addNumbers(a: 5, b: 3)
print("Sum using function: \(sumFunction)")

// Closure to add two numbers
let addClosure: (Int, Int) -> Int = { (x, y) in
  return x + y
}

let sumClosure = addClosure(5, 3)
print("Sum using closure: \(sumClosure)")

Key Points

  • Functions in Swift can take parameters and return values, making code reusable.
  • Closures are self-contained blocks of functionality that can be assigned to variables.
  • Both functions and closures can perform the same tasks, such as adding two numbers.
  • Closures use a concise syntax and are useful for inline or short operations.