Swift Introduction | Function Literals and Closures | Function Literals

Closures require passing a function as a value. You can define a function in advance and pass it as an argument, as in the previous example.

For a simple process used in only one place, defining a separate function can be unnecessary. Instead, write the function directly as an argument with a function literal.

{ ... process ... }

In practice, arguments are commonly included.

{ arguments in ... process ... }

Separate multiple arguments with commas. A function literal lets you provide the required function without defining it beforehand.

func printResult(function:(num:Int)->Int, n:Int) {
    print(function(num: n))
}

printResult({n in n * 2}, n: 10)

printResult({n in
    var re:Int = 0
    for num in 0...n {
        re += num
    }
    return re
}, n: 100)

This example calls the previously defined printResult function. It no longer uses a separate calc function. Instead, each call provides a function literal directly.

When the result comes from a single expression, write the literal on one line. Multiline processing is more complex but follows the same principle.

Closures and function literals may initially seem difficult. Remember that they treat functions as values, and experiment by modifying the examples.