In Swift how to call a method with parameters on GCD main thread?


In Swift, you can easily call a method along with parameters on the main thread through GCD. You can use the DispatchQueue.main.async method to execute a method on the main thread. Let's learn how to achieve this in Swift. Also, you can call a method with parameters after a delay using the DispatchQueue.main.asyncAfter method.

Grand Central Dispatch (GCD)

In iOS, macOS, and other Apple operating systems, Grand Central Dispatch (GCD) is a low-level C API that offers effective, system-wide control of concurrent processes. It is constructed on top of the dispatch queues and thread management primitives at a lower level.

Dispatch queues are a tool used by GCD to organize tasks. A data structure called a dispatch queue is used to store a list of tasks that must be carried out. Worker threads can perform tasks that have already been added to a queue.

Executing a Task on the Main Queue

In this example, we will implement a method that takes a parameter. After that, we will see how to call that method using the DispatchQueue.main.async method. Here is an example.

This is the syntax for executing the task on the main queue asynchronously.

DispatchQueue.main.async {
   // write the code here to update the user interface.
}

How to Call a Method on the Main Thread?

Example

// defines a method that takes a parameter
func greeting(fullName: String) {
   let message = "Good morning, \(fullName)"
   print(message)
}

// Call the method on the main thread using GCD
DispatchQueue.main.async {
   self.greeting(fullName: "Alex Murphy")
}

Output

Good morning, Alex Murphy

In this example, we define a method called greeting that takes one parameter: fullName of type String. We then call this method on the main thread using GCD by wrapping the method call inside DispatchQueue.main.async. The parameter is passed as arguments to the method call.

How to Call a Method with Parameters with Closure?

In this example, we will create a method to find the max value from an array that returns the max value using a closure. Here is an example.

Example

import UIKit
func findMax(_ array: [Int], performMax: @escaping ((Int) -> Void)) {
   var maxValue: Int = 0
   for value in array {
      if value > maxValue {
         maxValue = value
      }
   }   
   performMax(maxValue)
}
let numberArray = [23, 34, 43, 68, 21, 9]
DispatchQueue.main.async {
   findMax(numberArray) { max in
      print("Max value: \(max)")
   }
}

Output

Max value: 68

How to Call a Method with Parameters on the Main Thread After a Delay?

In this example, we will create a method to find the max value from an array that returns the max value using a closure. We will call this method after a delay on the main thread. Here is an example.

Example

import UIKit
func findMax(_ array: [Int], performMax: @escaping ((Int) -> Void)) {
   var maxValue: Int = 0
   for value in array {
      if value > maxValue {
         maxValue = value
      }
   }    
   performMax(maxValue)
}
let numberArray = [23, 34, 43, 68, 21, 9]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
   findMax(numberArray) { max in
      print("Max value: \(max)")
   }
}

Output

Max value: 68

Conclusion

In conclusion, to call a method with parameters on the main thread using GCD in Swift, you can wrap the method call inside a block passed to DispatchQueue.main.async. This will schedule the block to be executed asynchronously on the main thread, allowing you to perform UI updates or other tasks that must be done on the main thread. Remember to pass the method parameters in the usual way as arguments to the method call inside the block.

Updated on: 24-Apr-2023

452 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements