← 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.

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
func add(a: Int, b: Int) -> Int {
    return a + b
}
let operation: (Int, Int) -> Int = add
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
func multiply(a: Int, b: Int) -> Int {
    return a * b
}
func apply(_ operation: (Int, Int) -> Int, to a: Int, and b: Int) -> Int {
    return operation(a, b)
}
print(apply(multiply, to: 3, and: 5))
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.