Line At A Time
Lesson 22: Functions
Functions Write your own function and call it twice.
1func wave() {
2 print("Hello!")
3 print("How are you?")
4}
5
6wave()
7wave()
Terminal
$ swift main.swift
Hello!
How are you?
Hello!
How are you?
Every line, explained
func wave() {
func defines a function: your own named block of code. Defining it does nothing on its own; it waits until somebody calls it. In a Swift script, define a function before the line that calls it.
print("Hello!")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Part of the wave function's body.
print("How are you?")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Also part of the body: the function prints two lines every time it runs.
}
This } closes the function.
wave()
Writing the function's name with round brackets calls it: Swift jumps up into wave, runs its body, then comes back here.
wave()
Calling it again runs the body again. Write once, use as many times as you like. That is the whole point of functions!