Promises in Swift for beginners

Last updated 78 days ago by Tibor Bödecs

swift

Sync vs async execution

Writing asynchronous code is one of the hardest part of building an app.

What exactly is the difference between a synchronous and an asynchronous execution? Well, I already explained this in my Dispatch framework tutorial, but here is a quick recap. A synchoronous function usually blocks the current thread and returns some value later on. An asynchronous function will instantly return and passes the result value into a completion handler. You can use the GCD framework to perform tasks sync on async on a given queue. Let me show you a quick example:

``` func aBlockingFunction() -> String { sleep(.random(in: 1...3)) return "Hello world!" }

func syncMethod() -> String { return aBlockingFunction() }

func asyncMethod(completion block: @escaping ((String) -> Void)) { DispatchQueue.global(qos: .background).async { block(aBlockingFunction()) } }

print(syncMethod()) print("sync method returned") asyncMethod { value in print(value) } print("async method returned")

// "Hello world!" // "sync method returned" // "async method returned" // "Hello world!" ```

As you can see the async method runs entirely on a background queue, the function won't block the current thread. This is why the async method can return instantly, so you'll always see the return output before the last hello output. The async method's completion block is stored for later execution, that's the reason why is it possible to call-back and return the string value way after the original function have returned.

What happens if you don't use a different queue? The completion block will be executed on the current queue, so your function will block it. It's going to be somewhat async-like, but in reality you're just moving the return value into a completion block.

``` func syncMethod() -> String { return "Hello world!" }

func fakeAsyncMethod(completion block: ((String) -> Void)) { block("Hello world!") }

print(syncMethod()) print("sync method returned") fakeAsyncMethod { value in print(value) } print("fake async method returned") ```

I don't really want to focus on completion blocks in this article, that could be a standalone post, but if you are still having trouble with the concurrency model or you don't understand how tasks and threading works, you should read the linked articles.

Read full Article