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

Function Types

A function type describes the shape of a function -- what it takes in and what it gives back -- so you can store a function in a variable just like a number or string.
Syntax
swift
let name: (ParamType) -> ReturnType = existingFunction

func functionName(_ op: (ParamType) -> ReturnType) {
    // call op(value)
}

Storing a Function in a Variable

Because functions are first-class values, a function can be assigned to a variable whose type matches its signature.

Example: Storing a Function in a Variable

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
}
// Declare a constant `operation` (a `(Int, Int) -> Int`), set to `add`
let operation: (Int, Int) -> Int = add
// Print `operation(3, 4)` to the console
print(operation(3, 4))

Passing a Function as an Argument

A function type can be used as a parameter type, allowing one function to receive another function as an argument.

Example: Passing a Function as an Argument

markup
// Define the function `multiply` taking `a`, `b` and returning an Int
func multiply(a: Int, b: Int) -> Int {
    // Return `a * b` from this function
    return a * b
}
// Define the function `apply` taking `operation`, `a`, `b` and returning an Int
func apply(_ operation: (Int, Int) -> Int, to a: Int, and b: Int) -> Int {
    // Return `operation(a, b)` from this function
    return operation(a, b)
}
// Print `apply(multiply, to: 3, and: 5)` to the console
print(apply(multiply, to: 3, and: 5))
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 that a function type is written as (ParamTypes) -> ReturnType, matching the function's signature exactly, including parameter types (not labels).
  2. Trying to assign a function with a different signature to a variable already typed for another function shape.
  3. Confusing a function type variable with actually calling the function -- you must add () with arguments to invoke it.
Chapter Summary
  • A function's type is written as (ParameterTypes) -> ReturnType.
  • Functions can be assigned to variables, passed as arguments, and returned from other functions.
  • This makes functions first-class values in Swift.
  • A function type variable is called just like a normal function, with parentheses and arguments.
🔒

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.