← 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.
Syntax
swift
func functionName(paramName: Type) -> ReturnType {
    return value
}

func functionName() {   // no return value
}

functionName(paramName: value)

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
// Define the function `greet` taking `name` and returning a String
func greet(name: String) -> String {
    // Return `"Hello, \(name)!"` from this function
    return "Hello, \(name)!"
}
// Print `greet(name: "Swift")` to the console
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
// Define the function `printBanner` taking `title`
func printBanner(title: String) {
    // Print "=== \(title) ===" to the console
    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
// Define the function `add` taking `a`, `b` and returning an Int
func add(a: Int, b: Int) -> Int {
    // Return `a + b` from this function
    return a + b
}
// Print `add(a: 3, b: 4)` to the console
print(add(a: 3, b: 4))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.