Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 146 ยท Functions and Closures

Functions

Learn to declare and call Swift functions - parameters, return values, implicit returns, Void, multiple results, throwing early, nested functions and the mistakes the compiler catches for you.

A function is a named piece of code that you can run whenever you need it, optionally giving it input and getting a result back. Functions are how you avoid repeating yourself, give a name to an idea, and break a big problem into small, testable steps. You have been calling functions since your first print, now it is time to write your own.

Swift functions look friendly at first and turn out to be remarkably flexible. This lesson covers the basics: declaring, calling, parameters, return values, Void, returning several results and nesting functions. The next lessons build on it: Argument Labels, Function Types and Closures.

Declaring and calling

A function declaration starts with func, then the name, a parameter list in parentheses and the body in braces. You call it by writing its name with arguments in parentheses.

Swift Your first functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both functions are called greet, and Swift tells them apart by their parameters. This is called overloading. The second call includes the label person:, a special feature of Swift that gets its own lesson (Argument Labels). For now, remember that the label is part of the call and you must write it.

Naming matters. Swift's naming style is lowerCamelCase, and function names read best as verbs (sendMessage) or, for functions that return a value, noun phrases (distance). A function that works well reads like a sentence at the call site: greet(person: "Ada").

Parameters and return values

Parameters are written as name: Type, separated by commas. The return type follows an arrow ->. A function with a return type must return a value of that type on every path through its body.

Swift Parameters and return values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

In area and isEven there is no return. When a function body consists of a single expression, Swift returns its value automatically: an implicit return. As soon as there are two or more statements, you need an explicit return. The _ before number in isEven removes the label at the call site: isEven(10) instead of isEven(number: 10).

Parameters are constants inside the function. You cannot assign to them, and the compiler tells you so. If you need a modifiable copy, create a local var:

Swift Parameters are constants (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: left side of mutating operator isn't mutable: 'start' is a 'let' constant. The fix is a local variable: var current = start, then loop with current. (The next lesson shows inout, which lets a function change the caller's variable on purpose.)

Swift A mutable copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Returning nothing: Void

A function without -> returns Void, which is just a type name for the empty tuple (). You rarely write it out. You can call such a function as a statement, and you cannot meaningfully use its result.

Swift is strict about unused results. If a function returns a value and you ignore it, the compiler warns you, because that often means a bug. Use _ = to say "I know, I don't need it", or mark the function @discardableResult if ignoring the result is normal.

Swift Unused results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

addItem returns the new count, but callers mostly ignore it, so @discardableResult keeps the code warning-free. If you remove that attribute and call addItem("milk", to: &shopping) on its own, the compiler warns that the result is unused. For a function like square, whose only job is its result, ignoring it is a real mistake, so the warning is exactly what you want.

Multiple results

When a calculation produces several values, return a tuple. Give the elements labels, and the call site reads clearly.

Swift Returning a labeled tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is optional because an empty list has no statistics, and guard let exits early in that case. A function that can fail for "no good reason to report" often returns an optional. If you want to say why it failed, use error handling instead.

Functions with many exits: guard and early return

A well-written function validates its inputs first and returns early, keeping the main logic unindented. guard is made for this.

Swift Early exits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each guard states a precondition and bails out if it fails. The constant base is declared without a value and assigned exactly once on every path of the switch; Swift verifies that it is initialized before use. This is definite initialization, and it is one of the compiler's quiet strengths.

Missing a return

If a function promises a value, every path must deliver one. The compiler checks this for you:

Swift Missing return (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get error: missing return in global function expected to return 'String'. The case number == 0 has no return. Add an else { return "zero" } and it compiles. A switch expression or an if expression (see if and else) makes this class of mistake much harder, because every branch has to produce a value:

Swift Fixed with an if expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Nested functions

A function can be declared inside another function. The inner function is private to its container, can use the container's local variables, and does not pollute the outer namespace. It is ideal for a helper that only makes sense in one place.

Swift Nested functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

(import Foundation is there because rounded() needs it to link on Linux.) money is visible only inside formatReceipt. The second half is a preview of something bigger: makeCounter returns its inner function next, and that function remembers the variable count even after makeCounter has finished. A function that captures variables from its surroundings is a closure, the topic of Closures, and a function that returns a function is explored in Function Types.

Recursion and global functions in main.swift

A function can call itself, which is called recursion (Recursion has a full lesson). In a main.swift file, which is what the TryIt editors compile, functions declared at the top level can be called before or after their declaration:

Swift Order of declarations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Functions can be used before their declaration in the same scope. Variables in top-level code are different: a global declared further down can be read by an earlier function without any compiler error and still hold its zero value, because the declaring line has not run yet. Declare variables before the code that uses them.

Documenting and designing functions

A few habits make functions pleasant to use.

  • Do one thing, with a name that says it. If the name needs "and", split the function.
  • Keep parameter lists short. More than three or four parameters usually hide a missing type.
  • Prefer returning values over printing. A function that returns a String can be tested, reused and formatted; one that calls print cannot.
  • Fail loudly and early. Validate with guard, return nil or throw for bad input.
  • Write a doc comment with /// above public functions. Documentation Comments covers the format.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a single-expression function body do in Swift?

    When the body is exactly one expression, Swift returns it implicitly. With two or more statements you write return explicitly.
  2. 2. What happens if you assign to a parameter inside a function?

    Parameters are let constants. Copy into a local var, or use an inout parameter if the function should modify the caller's variable.
  3. 3. What does the compiler do when you ignore the result of func square(_ n: Int) -> Int by calling square(5) on its own line?

    Unused results produce a warning. Write _ = square(5) to ignore deliberately, or mark the function @discardableResult.
  4. 4. What is the type of a function declared without ->?

    A function that returns nothing returns Void, a typealias for (). Never is a different type used for functions that do not return at all.
  5. 5. Why is a nested function useful?

    A nested function is a private helper: it is invisible outside its container but can read and capture the container's locals.

Summary

  • Declare a function with func name(parameter: Type) -> ReturnType { ... } and call it with name(parameter: value).
  • A function whose body is a single expression returns it implicitly; otherwise use return.
  • Parameters are constants; copy to a local var when you need to change a value.
  • A function without -> returns Void; ignored results warn unless you write _ = or use @discardableResult.
  • Return a labeled tuple for several results, an optional when there may be no result, and use guard for early exits.
  • The compiler enforces that every path returns a value (missing return).
  • Nested functions are private helpers that can capture local variables.

Next: Argument Labels and Parameter Names