Start learning free

LESSON 34 OF 349 · FUNCTIONS I

Why Functions in Swift

Lesson

Now that we've learned about functions, let's see why they are so important in our prgrammers' 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

    Why Functions in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free