Lesson 10 of 15

Closures

Closures

Closures are self-contained blocks of functionality that can be passed around. In Swift, functions are first-class values — they can be stored in variables and passed as arguments:

let double = { (x: Int) -> Int in x * 2 }
print(double(5))  // 10

Closures as Function Parameters

func applyTwice(_ f: (Int) -> Int, _ x: Int) -> Int {
    return f(f(x))
}

print(applyTwice({ n in n + 3 }, 10))  // 16

Trailing Closure Syntax

When a closure is the last argument, you can place it outside the parentheses:

applyTwice(10) { n in n + 3 }  // 16

Your Task

Write a function applyTwice that takes a function f: (Int) -> Int and an integer x, and returns the result of applying f to x twice (i.e., f(f(x))).

JS Transpiler loading...
Loading...
Click "Run" to execute your code.