Async in Swift 101
This is the first article of a series that will explain what is asynchronous programming, why we should use it and how to solve some of the most common problems in Swift.
Synchronous vs Asynchronous programming
Synchronous: Executing codes line by line in order. (instantly)
Asynchronous: Executing codes or tasks in parallel. (whenever possible)
Here is an example;
In synchronous code, you would expect to see 1, 2, 3. Because of Asynchronous code block, this code prints 1, 3, 2.
So, why do we use it? There are some task which takes too long to do such as File I/O, database operations, image/video processing or network operations. If you do these long running tasks in synchronous way, you would not be able to do anything else until it finishes. You would have to wait so long. Imagine you are using Instagram, you opened the app and you cannot go to profile menu or settings or even scroll down. Because app has to download all images first and then you can scroll. Now, you see how important it is.
Thanks to Apple, Swift already has great tools to do the job. So that developers can easily build multi-threaded applications. A little warning here, Asynchronous does not mean multi-threaded. A single-threaded application can also run code asynchronously. Well back to the topic, most of the modern programming languages provide high-level abstractions for asynchronous operations and multi-threading. So, do not worry about Threads. In swift, we have DispatchQueues, DispatchGroups, DispatchWorkItem …etc. And every one of them serves different purpose and solves different problems.
In the next article, I will write about DispatchQueue in more detail. What problems it can solve, What problems it can cause and how to solve them. Any feedback would be appreciated. Please, reach me out for your questions.