Swift: Call back functions

Swift Callback Review

Swift is a powerful programming language that is growing in popularity every day. If you’re not familiar with it, now is the time to start learning. One of the features of Swift that makes it so powerful is its call back functions. In this article, we’ll take a look at what call back functions are and how they can be used to your advantage in your programming projects.

What is a Swift Function?

What are callbacks in Swift? - Quora

Image Source: Link

Functions in Swift are just a syntactic sugar over functions defined in the global scope. Functions can be defined in the same file as the code they will be used in, or they can be defined in a separate file. The following code snippet defines a function called add that takes two integers and returns their sum:

func add(a: Int, b: Int) -> Int { return a + b }

You can call this function like so:

add(10, 20)

The result of calling add() is 30.

How to define a Swift Function?

In Swift, a function is defined by specifying the name of the function followed by the parentheses and the parameter list. After the parentheses, you put in the code that will execute when someone calls your function.

To call a function, you use the parentheses, followed by the name of the function and the argument list. The first argument is always the function’s name and the second argument is always an input value.

Here’s an example of a simple function that prints “Hello World!”

func printHelloWorld() { print(“Hello World!”) }

If you want to call this function with a string as its first argument, you would use this code: printHelloWorld(“world”)

Calling a Swift Function

In Swift, functions are first-class data structures and you can treat it just like any other type. To call a function, you simply use the function name followed by the parentheses:

var result = func1(arg1, arg2)

Swift also allows you to call functions from within other functions. This is done by using the function keyword followed by the name of the function you want to call, then the parentheses again:


Returning Values from a Swift Function

The following example shows how to return a value from a Swift function.

func add(a: Int, b: Int) -> Int { return a + b }

When you call the add function, it returns an integer value. You can use this value to calculate other results.


The Swift programming language has a wealth of functions that you can use it to achieve specific tasks. In this article, we have shown you some of the most commonly used call back functions in Swift. By understanding how these functions work and how to use them, you will be able to create more dynamic and efficient code.


1. What is a callback function in Swift?

Answer: A callback function in Swift is a function that is passed as an argument to another function and is invoked after the completion of some operation. Callbacks are often used for asynchronous operations, such as network requests or long-running tasks, to handle the result once the task is complete.

2. How do you define and use a callback function in Swift?

Answer: To define and use a callback function in Swift, you declare a function that takes another function as a parameter. Here’s an example:

func fetchData(completion: @escaping (String) -> Void) {

// Simulating a network request with a delay

DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {

let data = “Fetched Data”





fetchData { result in

print(result) // Outputs: Fetched Data


In this example, fetchData takes a callback function named completion that is called with a String parameter after a simulated network request.

3. What does @escaping mean in the context of callback functions in Swift?

Answer: The @escaping keyword in Swift indicates that a closure, such as a callback function, can outlive the function it was passed to. This is necessary when the closure is stored or executed asynchronously after the function has returned.

func performTask(completion: @escaping () -> Void) {

DispatchQueue.global().async {

// Perform some task





performTask {

print(“Task completed”)


In this example, completion is marked with @escaping because it is executed asynchronously on a background queue.

4. How do you handle errors in callback functions in Swift?

Answer: To handle errors in callback functions, you can use a callback with a result type that can represent both success and failure. Swift’s Result type is commonly used for this purpose.

enum NetworkError: Error {

case badURL

case requestFailed



func fetchData(completion: @escaping (Result<String, NetworkError>) -> Void) {

// Simulating a network request with a delay

DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {

let success = true // Simulate success or failure

if success {

completion(.success(“Fetched Data”))

} else {






fetchData { result in

switch result {

case .success(let data):

print(data) // Outputs: Fetched Data

case .failure(let error):

print(“Error: \(error)”)



In this example, the fetchData function calls the completion handler with a Result that either contains the fetched data or an error.

5. Can you use trailing closure syntax with callback functions in Swift?

Answer: Yes, Swift supports trailing closure syntax, which allows you to write cleaner and more readable code when a function’s last parameter is a closure. Here’s an example:

func performOperation(with value: Int, completion: @escaping (Int) -> Void) {

let result = value * 2




// Using trailing closure syntax

performOperation(with: 5) { result in

print(“Result: \(result)”) // Outputs: Result: 10


In this example, the closure completion is written outside the parentheses of the performOperation function call, using trailing closure syntax.

Leave a Reply

Your email address will not be published. Required fields are marked *