Swift Functions
A function is a named block of code that performs one task. A program runs a function by writing a call to it.
A function that prints
The definition starts with func and the name greet. The call under the definition runs the body once.
func greet() {
print("Hello from greet")
}
greet()Parameters and labels
The definition lists two Int parameters named a and b. The call passes 2 for a and 3 for b and the body prints the sum.
func add(a: Int, b: Int) {
print(a + b)
}
add(a: 2, b: 3)One function, two calls
The same definition runs twice in this program. Each call passes different arguments and prints a different sum.
func add(a: Int, b: Int) {
print(a + b)
}
add(a: 2, b: 3)
add(a: 10, b: 4)A function calling a function
The showTitle function calls showLine inside its own body. One outer call prints three lines in order.
func showLine() {
print("---")
}
func showTitle() {
showLine()
print("Report")
showLine()
}
showTitle()A call without labels
This call leaves out both argument labels. The compiler rejects the program with one error.
func add(a: Int, b: Int) {
print(a + b)
}
add(2, 3)Example
func badge(name: String, level: Int) {
print("\(name) is level \(level)")
}
badge(name: "Ana", level: 2)
badge(name: "Bo", level: 5)Key points
- A function groups code under one name.
- The func keyword starts a function definition.
- The definition lists parameters inside parentheses.
- Each parameter has a name and a type.
- Curly braces hold the body of a function.
- A call writes each argument with its label first.
- One function can call another function.
In this example, the badge function takes a name and a level as its parameters. The first call passes Ana and 2 and prints Ana is level 2. The second call passes Bo and 5 and prints Bo is level 5.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What does a call write for each argument?