Sobes.tech
Junior — Middle

Explain the difference between a closure and a function in programming.

sobes.tech AI

Answer from AI

A function is a block of code that performs a specific task and can accept parameters and return a result.

A closure is a function that captures and retains access to variables from its surrounding scope, even after that scope has finished execution.

Example in Swift:

func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    let incrementer: () -> Int = {
        total += amount
        return total
    }
    return incrementer
}

let incrementByTen = makeIncrementer(amount: 10)
print(incrementByTen()) // 10
print(incrementByTen()) // 20

Here, incrementer is a closure that maintains the state total between calls, even after makeIncrementer has finished. A regular function does not have this behavior.

Explain the difference between a closure and a… - sobes.tech