With the recent introduction of Swift 5.5 in WWDC21, developers all around the world are celebrating as finally, finally, async/await is now on Swift.
So, why is this a big deal?
Currently, if you’re doing something that requires a lot of asynchronous code, your code might have something like this:
func doComplexActions(completion: @escaping() - & gt; Void) {
action1 {
boolResult in
if boolResult {
action2(boolResult) {
intResult in
action3(intResult) {
stringResult in
print(stringResult)
completion()
}
}
} else {
action4 {
stringResult in
print(stringResult)
completion()
}
}
}
}
func action1(completion: @escaping(Bool) - & gt; Void) {
// async code here
completion(boolResult)
}
func action2(_ result: Bool, completion: @escaping(Int) - & gt; Void) {
// async code here
completion(intResult)
}
func action3(_ result: Int, completion: @escaping(String) - & gt; Void) {
// async code here
completion(stringResult)
}
func action4(completion: @escaping(String) - & gt; Void) {
// async code here
completion(stringResult)
}
But with async/await, we can further simplify that to a more concise and readable format.
Let’s break down into how we can convert our current code to the Async/Await pattern.
1. Replace the completion handler syntax with the async syntax
func action1(completion: @escaping (Bool) -> Void) {
// async code here
completion(boolResult)
}
func action1() async -> Bool {
// async code here
return boolResult
}
2. Replace the closure syntax with await syntax
action1() { boolResult in
// ...
}
let boolResult = await action1()
// ...
3. Repeat for other functions
func doComplexActions() async {
let boolResult = await action1()
if boolResult {
let intResult = await action2(boolResult)
let stringResult = await action3(intResult)
print(stringResult)
} else {
let stringResult = await action4(intResult)
print(stringResult)
}
}
func action1() async -> Bool {
// async code here
return boolResult
}
func action2(_ result: Bool) async -> Int {
// async code here
return intResult
}
func action3(_ result: Int) async -> String {
// async code here
return stringResult
}
func action4() async -> String {
// async code here
return stringResult
}
And we’re done! As you can see, with async/await, our code is now more streamlined. We’re able to better see the scope of the conditional and the sequence of actions within it.
Cool right? that’s just one of the updates we have with Swift 5.5! Share more with us.
More from
Engineering
Importance of Design QA workflow
Marvin Fernandez, Engineering Manager
SQA questions to ponder
Joy Mesina, QA
Writing a Software Test Plan
Ron Labra, Software Quality Analyst