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
func add(a: Int, b: Int) -> Int {
return a + b
}
let operation: (Int, Int) -> Int = add
print(operation(3, 4))
Login to try C/C++/Java/PHP code in the editor
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
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))
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that a function type is written as
(ParamTypes) -> ReturnType, matching the function's signature exactly, including parameter types (not labels). - Trying to assign a function with a different signature to a variable already typed for another function shape.
- 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: