Writing #Async code with #Swift
I’ve just started to learn Swift, and I’m going to start posting some coding nuggets that for me, are quite a novel way that the language handles things. Async code is my first post on this language, since it’s really crucial for modern software development.
So, I’m working with the PlayGround, and in order to write code in the playground that does not immediately execute, you need to add two lines:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
which means that the Playground may continue executing indefinitely.
Now, lets say we want to write some code that does something after 1 second (without freezing the UI), we would write:
DispatchQueue.global().async
{
sleep(1)
// Do Something
}
Then, if you wanted to wrap this in a function that, does something really simple, like add one to a number, then you would write:
func addOneAsync( input : Int, completion: @escaping (Int) -> Void){
DispatchQueue.global().async
{
sleep(1)
completion(input+1)
}
}
Since the last parameter is a function, it can be called using the following syntax;
addOneAsync(input: 3){ output in
print(output)
}
print(“hello”)
the output is then appears as
hello
4
Note, that the 4 appears after the hello, after 1 second, because the execution was deferred to a background thread. – Obviously, this is a contrived example, since you would never need to delay execution of a simple addition, but imagine you are doing a HTTP request, or a complex database query here.