Overview
A function is a named block of code that performs a specific task. Instead of writing the same lines again and again, you put those lines inside a function and call the function whenever you need that task to happen.
Functions are one of the first tools that help your Swift code become more organized. They make code easier to reuse, easier to test, and easier to read.
Basic Function Syntax
A simple Swift function starts with the func keyword, followed by a name, parentheses, and a code block:
func sayHello() {
print("Hello!")
}
sayHello()The function definition tells Swift what the function does. The line sayHello() calls the function, which means Swift runs the code inside it.
Functions Reduce Repetition
Without functions, repeated code spreads through your project quickly:
print("Welcome to the app")
print("Load user settings")
print("Show home screen")
print("Welcome to the app")
print("Load user settings")
print("Show home screen")A function lets you name those steps once:
func startApp() {
print("Welcome to the app")
print("Load user settings")
print("Show home screen")
}
startApp()
startApp()Now the repeated idea has a name: startApp. That name is easier to understand than a loose cluster of repeated print statements.
Functions with Parameters
Parameters let you pass information into a function. Here is a function that greets a specific person:
func greet(name: String) {
print("Hello, \\(name)!")
}
greet(name: "Chris")
greet(name: "Maya")The parameter is name, and its type is String. Each time you call the function, you provide a different value for that parameter.
Multiple Parameters
Functions can take more than one parameter. Separate them with commas:
func greet(name: String, times: Int) {
for _ in 1...times {
print("Hello, \\(name)!")
}
}
greet(name: "Chris", times: 3)This function uses both parameters: name controls who gets greeted, and times controls how many greetings are printed.
Functions with Return Values
A function can also send a value back to the code that called it. You write the return type after an arrow:
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
let total = add(4, 6)
print(total)The -> Int part means this function returns an Int. The return keyword sends the result back.
For short single-expression functions, Swift can often infer the return expression:
func doubled(_ number: Int) -> Int {
number * 2
}Argument Labels
Swift function parameters can have argument labels. Labels make function calls read more like sentences.
func sendMessage(to name: String, message: String) {
print("Sending '\\(message)' to \\(name)")
}
sendMessage(to: "Chris", message: "Welcome!")Inside the function, the parameter is called name. At the call site, the label is to.
If you do not want an argument label, use an underscore:
func square(_ number: Int) -> Int {
number * number
}
let result = square(5)Default Parameter Values
You can give a parameter a default value. Then callers can omit it when the default is good enough:
func log(_ message: String, level: String = "info") {
print("[\\(level)] \\(message)")
}
log("App started")
log("Network request failed", level: "error")Default parameters are useful when a function has a common path and a less common customization.
Early Returns with Guard
Functions are a natural place to validate input. A guard statement can exit early when a required condition is not met:
func printUsername(_ username: String?) {
guard let username else {
print("No username found")
return
}
print("Username: \\(username)")
}
printUsername(nil)
printUsername("chris")The early return keeps the rest of the function focused on the success path.
Common Mistakes
Trying to use a value returned from a void function
A function that does not declare a return type returns Void. It performs an action, but it does not give you a value to store.
Forgetting argument labels
Swift usually requires argument labels at the call site. If the function is greet(name:), call it with greet(name: "Chris"), not greet("Chris").
Making functions do too much
If a function is hard to name, it may be doing too many things. A good beginner rule is that a function name should clearly describe the one main task it performs.
Quick Reference
| Syntax | What It Does |
|---|---|
func name() { } | Defines a function with no parameters and no return value |
func greet(name: String) | Defines a function with one parameter |
func add(_ a: Int, _ b: Int) -> Int | Defines a function that returns an integer |
return value | Sends a value back to the caller or exits early from a void function |
to name: String | Uses to as the external argument label and name inside the function |
_ number: Int | Removes the external argument label at the call site |
level: String = "info" | Provides a default parameter value |
Summary
- Functions are named blocks of reusable code.
- Use functions to reduce repetition and make code easier to understand.
- Parameters let you pass values into a function.
- Return values let a function send a result back.
- Argument labels make Swift function calls easier to read.
- Default parameter values make common calls shorter.
- Use early returns to keep validation and edge cases clear.
The best way to get comfortable with functions is to look for repeated code in your own projects. When you see the same steps appearing more than once, give those steps a clear name and turn them into a function.