Start learning free

LESSON 28 OF 415 · FUNCTIONS I

Functions in Swift: Defining and Calling with func

Lesson Read the full explanation

A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in Swift:

func functionName() {
    // function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • func keyword followed by functionName, which is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that Swift executes whenever the function is called.

It consists of one or more Swift statements placed inside curly brackets {} (where we have our Swift comment).

Here's an example of a function:

func sayHello() {
    print("Hello World")
}

This function declares no return type (so it returns Void), which means the function is not returning any value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our print("Hello World").

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
func sayHello() {
    print("Hello World")
}

// Function call:
sayHello() // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SWIFT · FUNCTIONS I

    Functions in Swift, explained

    What a function is

    A function is a named block of code that does one job. Instead of writing the same lines wherever you need them, you write them once inside a function and use the function's name when you want them to run. Functions also let you split a long program into small pieces that are each easy to read.

    Here is the shape of a function definition in Swift:

    func functionName() {
        // function body
    }
    

    It has two parts:

    • The header. The keyword func, then the function's name, then a pair of parentheses. The parentheses are empty for now. Later lessons put inputs there.
    • The body. The statements the function runs, wrapped in curly braces {}.

    A complete example:

    func sayHello() {
        print("Hello World")
    }
    

    The body is indented by one level. Swift doesn't require indentation, but it makes it obvious which lines belong to the function.

    This function has no -> Type after the parentheses, so it returns nothing. It only has an effect, printing a line.

    Defining is not running

    If you put only the definition above in a program, nothing is printed. A definition describes what the function does, and the body doesn't execute until something calls the function. A call is the function's name followed by parentheses:

    func sayHello() {
        print("Hello World")
    }
    
    sayHello() // Hello World
    sayHello() // Hello World
    

    Each call runs the whole body again, from the first statement to the last, so a function can be called as many times as you need.

    The parentheses matter. Writing just sayHello refers to the function itself instead of calling it, and Swift reports a statement like that as an error: function is unused.

    The exercise, step by step

    The starter code gives you an empty mainFunction, the lesson's main program. You add a function above it and call it from inside.

    1. Define sayHello above mainFunction. Write func sayHello() { }. At this point it exists but does nothing.
    2. Fill in the body. A single print("Hello everybody!") goes between the braces. print ends its output with a new line.
    3. Call it from mainFunction. Without the call sayHello() the definition would never run, so nothing would be printed.

    The solution in Swift

    func sayHello() {
        print("Hello everybody!")
    }
    
    func mainFunction() {
        sayHello()
    }
    

    Notice that mainFunction is itself a function, and it calls another one. Functions calling functions is how larger programs are built.

    The order of definitions at the top level of a file is flexible for functions, so sayHello could even be declared below mainFunction. Keeping helpers above the code that uses them reads more naturally, and the lesson does it that way.

    Common mistakes

    • Forgetting the braces. The body must be inside { and }. A header with no body is a compile error.
    • Forgetting the call. If the function is defined and the output is empty, check that something calls it.
    • Calling without parentheses. sayHello is not a call. Write sayHello().
    • Misspelling the name. Swift is case-sensitive, so sayhello() and sayHello() are different names.
    • Wrong text. The tests compare the printed text exactly, including capital letters and the exclamation mark.

    Key takeaways

    • A function is defined with func, a name, parentheses and a body in braces.
    • A definition only declares the function. A call such as sayHello() runs it.
    • A function with no return type returns nothing, and every call runs the full body.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free