← Back to Swift Course | Chapter 4: Functions | Lesson 1 of 7

Function Basics

A function is a named recipe of steps you can run whenever you want, just by calling its name.

Declaring and Calling a Function

A function is defined with func, a name, parameters in parentheses, and an optional return type after ->.

Example: Declaring and Calling a Function

markup
func greet(name: String) -> String {
    return "Hello, \(name)!"
}
print(greet(name: "Swift"))

Functions Without a Return Value

A function that only performs an action, without producing a value, simply omits the -> return type entirely.

Example: Functions Without a Return Value

markup
func printBanner(title: String) {
    print("=== \(title) ===")
}
printBanner(title: "Welcome")

Multiple Parameters

A function can take several parameters, each with its own name and type, separated by commas.

Example: Multiple Parameters

markup
func add(a: Int, b: Int) -> Int {
    return a + b
}
print(add(a: 3, b: 4))
Common Mistakes
  1. Forgetting the -> arrow before the return type, writing func add(a: Int, b: Int) Int instead of func add(a: Int, b: Int) -> Int.
  2. Omitting return inside a multi-statement function body; only single-expression bodies can skip it implicitly.
  3. Calling a function without its argument labels when they are required, e.g. calling add(a, b) instead of add(a: a, b: b).
Chapter Summary
  • Functions are declared with func name(parameters) -> ReturnType { }.
  • Parameters and their types are listed in parentheses, separated by commas.
  • A function with no meaningful return value omits the -> ReturnType part (implicitly returning Void).
  • Calling a function uses its name followed by arguments in parentheses, using labels by default.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.