Ad space (banner)
๐ŸฆSwift Lessons
Lesson 29 / 68

Higher-Order Functions (Passing a Function as an Argument)

In this lesson you will learn how to pass a function as an argument in Swift, so you can treat behaviour itself as a reusable part. This is for anyone searching for "Swift higher-order functions how to use".

Passing another function (a closure) as an argument is what makes something a higher-order function. Picture handing over the rules for a job and letting someone else do the work. Giving a comparison rule to .sorted(by:) is the classic example.

The sample code sorts in descending order by passing the ordering criterion as a closure, as in nums.sorted(by: { a, b in a > b }). The map you met earlier is in fact another higher-order function.

A common stumbling block for beginners is closure syntax. Until { a, b in a > b } feels natural, the difference from an ordinary function definition can be confusing. A closure can also capture variables, so it can carry surrounding values with it.

In real-world development the same idea applies to designs that swap behaviour by situation - an important feature behind Swift's readability.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)