Async/Sync in swift

Updated 3 July 2023

Save

Async/Sync are two different things in swift. Async stands for Asynchronous and sync means Synchronous.

We can use both Async and sync in the code but both will use in different places.

The major difference between Async and sync are:

Sync: When the code reaches the sync statement it will block the current queue until that task completes.

Once the task returns/completes, control is returned to the caller, and the code that follows the sync task will continue.

Async: When the code reaches the Async statement it will not block the current queue it will initiate that task and move forward. The initiated task will execute in parallel.

It immediately returns control back to the caller without waiting for the contents of the async closure to execute.

Basically, we can prevent concurrency while initiating multiple threads simultaneously by using Async.

If we do not use the async in this type of case the app might crash or stuck at that point.

Let’s understand this with an example.

In the below example, we have called the test2 function and then we have called the test1 function.

But as you can see in the log, it prints the value of 2nd function and then the first function.

This is because we have used the Async in test2 function so it will not wait for return value and executes the next function.

Conclusion

I hope this blog helps you to understand the functionality of Async/sync in swift.

Thanks for Reading !!

For more blogs click here

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home