0
0
Swiftprogramming~5 mins

Why functions are first-class in Swift

Choose your learning style9 modes available
Introduction

Functions are first-class in Swift so you can use them like any other value. This means you can store them, pass them around, and use them easily.

When you want to pass a piece of work to another part of your code.
When you want to store different actions in a list or variable.
When you want to create flexible code that can change behavior.
When you want to return a function from another function.
When you want to simplify repeated tasks by reusing code blocks.
Syntax
Swift
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

let sayHello = greet  // Assign function to a variable

let message = sayHello("Alice")  // Call function via variable

You can assign a function to a variable or constant.

You can pass functions as parameters or return them from other functions.

Examples
Assigning a function to a variable and calling it later.
Swift
func add(a: Int, b: Int) -> Int {
    return a + b
}

let sumFunction = add

let result = sumFunction(3, 4)  // result is 7
Passing a function as a parameter to another function.
Swift
func perform(operation: (Int, Int) -> Int, a: Int, b: Int) -> Int {
    return operation(a, b)
}

let multiply = { (x: Int, y: Int) in x * y }

let product = perform(operation: multiply, a: 5, b: 6)  // product is 30
Returning a function from another function.
Swift
func makeIncrementer() -> (Int) -> Int {
    return { number in number + 1 }
}

let increment = makeIncrementer()

let newNumber = increment(7)  // newNumber is 8
Sample Program

This program shows how to assign a function to a variable and call it.

Swift
func greet(name: String) -> String {
    return "Hello, \(name)!"
}

let sayHello = greet

print(sayHello("Bob"))
OutputSuccess
Important Notes

Functions being first-class means they behave like any other value.

This feature helps make your code more flexible and reusable.

Summary

Functions can be stored in variables or constants.

Functions can be passed as arguments or returned from other functions.

This makes Swift code more powerful and easier to organize.