In the tutorials so far in this course, you've used functions many times. In this tutorial, you'll see how to create new ones! After that, you'll learn about loops in Swift, one of the most important concepts in programming. In plain English, loop-statements correspond to “Do this action X times.” or “Keep doing that action as long as this condition is true.”
Your own functions!
Remember functions like uppercased() that you can execute in Swift? Well, good news – you will learn how to write your own functions now!
A function is a sequence of instructions that Swift should execute. Each function in Swift starts with the keyword func, is given a name, and can have some parameters. Let's give it a go.
type=codeblock|id=swift_functions1|autocreate=swift4func hi() {print("Hi there!")print("How are you?")}hi()
Output:
Hi there!How are you?
Okay, our first function is ready!
You may wonder why we've written the name of the function at the bottom. The first time (lines 3-6 in the screenshot), we're defining what the function does. The second time (line 8), we're calling the function, i.e. asking Swift to actually execute the function.
Note that because Swift reads the file and executes it from top to bottom. When Swift is executing the function, if it hasn't yet found the definition, it will throw an error of unresolved identifier. Hence, we define the function before calling it.