Concurrency in Swift
Swift has built-in support for writing asynchronous and parallel code in a structured way.?Asynchronous code?can be suspended and resumed later, although only one piece of the program executes at a time. Suspending and resuming code in your program lets it continue to make progress on short-term operations like updating its UI while continuing to work on long-running operations like fetching data over the network or parsing files.
Wait before I go further with concurrency, I would like to talk to Parallelism, we usually get confused with concurrency and parallelism. Concurrency is what explained above (asynchronous) and
Parallel code?means multiple pieces of code run simultaneously — for example, a computer with a four-core processor can run four pieces of code at the same time.
Note
If you’ve written concurrent code before, you might be used to working with threads. The concurrency model in Swift is built on top of threads, but you don’t interact with them directly. An asynchronous function in Swift can give up the thread that it’s running on, which lets another asynchronous function run on that thread while the first function is blocked. When an asynchronous function resumes, Swift doesn’t make any guarantee about which thread that function will run on.
Ok we had the theory, let jump into the how to
Write a asynchronous method:
func shouldGoToHeaven(karma: [String]) async -> Bool {
//you know the return value, for me I am gonna lie and keep it true ;)
let result: Bool = //godly functon that will say true
return result
}
I am sure you can see what make this method async
领英推荐
Yes, you are right the async keyword used make this method async, an async method does one of these three things, run to completion, throw an error, or never return.
to make an async method able to throw an error, all you got to do is add throws before async
Let's see how we can call the method
let goToHeaven = await shouldGoToHeaven(karma: ["Coding"])
if goToHeaven{
// for sure and we know why
navigateToHeaven()
}
to call an async method all we need to do is use await while calling the method and the execution will wait for the response to come and then proceed with the next line of code.
Although there is one small catch, the method which is calling the async method has to be async.
Don't panic there is a way to call async methods from methods which aren't/cannot be async.
I will talk about that in the next article. Go ahead and try this first. Here is the link to the next(once it's out) article.
Happy Coding