Functions can be used like any other type in Swift. This means you can store them in variables, pass them as input to other functions, or return them from functions. It helps you write flexible and reusable code.
0
0
Functions as types in Swift
Introduction
When you want to pass a small piece of work (a function) to another function to run later.
When you want to store different actions in variables and choose which one to run.
When you want a function to create and return another function.
When you want to simplify your code by using functions as building blocks.
Syntax
Swift
let variableName: (InputType) -> ReturnType = functionName // Example: func sayHello(name: String) -> String { return "Hello, \(name)!" } let greet: (String) -> String = sayHello
The type of a function is written as (InputType) -> ReturnType.
If a function takes multiple inputs, list them inside parentheses separated by commas, like (Int, Int) -> Int.
Examples
Here,
mathOperation is a variable that holds a function taking two Ints and returning an Int.Swift
func add(a: Int, b: Int) -> Int { return a + b } let mathOperation: (Int, Int) -> Int = add
greet stores a function that takes a String and returns a greeting String.Swift
func sayHello(name: String) -> String { return "Hello, \(name)!" } let greet: (String) -> String = sayHello
This function returns another function. We store it in
increment and call it with 7.Swift
func makeIncrementer() -> (Int) -> Int { func addOne(number: Int) -> Int { return number + 1 } return addOne } let increment = makeIncrementer() print(increment(7))
Sample Program
This program stores the multiply function in a variable and uses it to multiply 4 and 5.
Swift
func multiply(a: Int, b: Int) -> Int { return a * b } let operation: (Int, Int) -> Int = multiply let result = operation(4, 5) print("Result: \(result)")
OutputSuccess
Important Notes
You can use functions as types to make your code more flexible and easier to change.
Functions as types are useful for callbacks, event handlers, and custom behaviors.
Summary
Functions can be treated like any other type in Swift.
You can store, pass, and return functions using their type signatures.
This helps write reusable and flexible code.