Start learning free

LESSON 34 OF 415 · FUNCTIONS I

Why Use Functions in Swift: Write Once, Call Often

Lesson Read the full explanation

Now that we've learned about functions, let's see why they are so important in our programmers' life:

Consider this: A student named Andy made a mistake and so his teacher told him to write this text 3 times on the whiteboard:

This is Andy
Andy made a mistake
Andy suffers the consequences

We would put this in a simple program like this:

print("This is Andy")
print("Andy made a mistake")
print("Andy suffers the consequences")

print("This is Andy")
print("Andy made a mistake")
print("Andy suffers the consequences")

print("This is Andy")
print("Andy made a mistake")
print("Andy suffers the consequences")

That's manageable. But what if the text consisted of more than 3 lines? And what if the teacher asked Andy to print it for 10 times or 100 times?

You can imagine that our code would get super long while executing 3 different instructions overall.


The story with functions:

This is where functions shine. We can write a function that prints the desired text and then just call the function for as many times as the teacher asks to:

func printMessage() {
	print("This is Andy")
	print("Andy made a mistake")
	print("Andy suffers the consequences")
}

printMessage()
printMessage()
printMessage()

Changing the story:

Need to print the text 3 more times? We call the function 3 more times instead of adding 9 lines to our program.

Need to change the student's name to Mike? We only change it inside the function instead of changing it in the whole program.

func printMessage() {
	print("This is Mike")
	print("Mike made a mistake")
	print("Mike suffers the consequences")
}

printMessage()
printMessage()
printMessage()
printMessage()
printMessage()

Note:

If you still don't like this code, especially the fact that we have 5 duplicate lines of code: printMessage(), you are correct! We will learn how we can make this even better with loops!


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check

    SWIFT · FUNCTIONS I

    Why Functions in Swift, explained

    The problem: repeated code

    Imagine a student who has to write three lines of text on a whiteboard three times. As a Swift program, the straightforward version repeats the same three print calls:

    print("This is Andy")
    print("Andy made a mistake")
    print("Andy suffers the consequences")
    
    print("This is Andy")
    print("Andy made a mistake")
    print("Andy suffers the consequences")
    
    print("This is Andy")
    print("Andy made a mistake")
    print("Andy suffers the consequences")
    

    Nine lines, but only three different instructions. This is manageable, until the text becomes ten lines long, or has to be repeated a hundred times. The program would grow with every repetition, and every line would have to be kept identical by hand.

    The fix: put the lines in a function

    A function lets you write the lines once and run them whenever you want, just by calling the function:

    func printMessage() {
        print("This is Andy")
        print("Andy made a mistake")
        print("Andy suffers the consequences")
    }
    
    printMessage()
    printMessage()
    printMessage()
    

    The output is the same as before. The three instructions now exist in exactly one place, and each printMessage() line stands for all three of them.

    What functions buy you

    • Repetition is cheap. Printing the text five times instead of three means two more calls, not six more lines.
    • A change is made once. If the student's name changes to Mike, you edit the three strings inside the function. Every call picks up the new text automatically.
    • Names explain intent. printMessage() says what happens at that point in the program, and the details are in the body for anyone who needs them.
    • Fewer copy-paste mistakes. When the same lines appear in ten places, it's easy to fix nine of them and forget the tenth.

    The calls themselves still repeat. Loops, which come later, remove that repetition too.

    The exercise, step by step

    The starter code is a mainFunction that already prints Sorry, I didn't hear you once. You add a function that introduces Andy, and call it before and after that line.

    1. Define introduceYourself above mainFunction. It has empty parentheses, a body in braces and no return type, so it returns nothing.
    2. Print the first line inside it: print("My name is Andy").
    3. Print the second line on the next line of the body: print("I love coding").
    4. Call it at the start of mainFunction. The call introduceYourself() runs both print lines.
    5. Call it again after the "Sorry, I didn't hear you" line. The introduction is printed a second time without a single line of it being repeated.

    The solution in Swift

    func introduceYourself() {
        print("My name is Andy")
        print("I love coding")
    }
    
    func mainFunction() {
        introduceYourself()
    
        print("Sorry, I didn't hear you")
    
        introduceYourself()
    }
    

    When mainFunction runs, it prints the following:

    My name is Andy
    I love coding
    Sorry, I didn't hear you
    My name is Andy
    I love coding
    

    If the introduction ever changes, only the body of introduceYourself needs editing, and both calls pick up the change. The text has to match the lesson exactly, including the words Andy and coding, because the tests compare the printed lines.

    Common mistakes

    • Defining the function and not calling it. The definition alone prints nothing.
    • Calling without parentheses. introduceYourself alone doesn't call the function, and Swift reports it as an error.
    • Copying the print lines into mainFunction as well. That repeats the code the function exists to avoid.
    • Wrong place for the calls. The first call goes before the Sorry, I didn't hear you line, and the second goes after it. Swapping them changes the output order.

    Key takeaways

    • A function holds code you want to reuse. You write it once and call it by name.
    • Changing the function's body changes every call at the same time.
    • Each call runs the entire body, in order, from top to bottom.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free