All lessons

Functions

8 min · Swift

Package code under a name so you can reuse it.

Swift · Functions0/5 cleared

Enemy 1 of 5

A function packages a piece of logic under a name so you can run it again without retyping the same code. Define one with func, followed by a name and a parameter list in parentheses. Each parameter needs a type, and if the function returns a value, the return type follows an arrow (-> Type) after the parameters — for example, func double(_ n: Int) -> Int declares a function named double taking one Int parameter and returning an Int.

The leading underscore before n (_ n: Int) is a distinctly Swift detail: by default, Swift functions require callers to write the parameter's name as a label at the call site (like double(n: 5)), which can make code very self-documenting for functions with several parameters. The underscore explicitly opts out of that requirement for a given parameter, letting you call the function as double(5) instead. You'll see both styles in real Swift code — labeled parameters when clarity matters (especially with multiple parameters of the same type), and underscore-prefixed ones when the meaning is already obvious from context.

return sends a value back to the caller and immediately stops the function from executing any further code in that block.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.

Stuck? Ask Rena

Your AI tutor that gives assistance.

Asking Rena in lessons is on Ultimate.