In Swift 5.5, Apple introduced Swift Concurrency, which is a completely new system for writing asynchronous code in Swift. Included with Swift Concurrency is async await, a system that makes writing asynchronous Swift functions a lot easier, among other things 🎉
❓But first, what are asynchronous functions, and why are they important?
Asynchronous functions perform tasks in the background while the system performs other tasks, and they're most commonly used when doing things like making API calls, downloading files, etc. That's because these tasks can start and finish very quickly 💨, very slowly 🐢, or somewhere in the middle🚶
To define an asynchronous function, all you need to do is add the async keyword in the function definition like this: func doSomething() async { }
And then to call an async function, call the function normally but precede the call with the await keyword like this: await doSomething()
But there's a catch! Calling an asynchronous function within a synchronous context, like in a button's action closure, will produce an error. In order to call an asynchronous function from a synchronous context, just wrap the call in a Task like this:
Button {
Task {
await doSomething()
}
}
You can also call an asynchronous function when a view appears by wrapping the call in a .task(_:) SwiftUI modifier.
🙋♂️ For experienced developers: How do you like async await? Do you prefer it to GCD? For new developers: Do you find async await confusing, or do you feel like you have a pretty good handle on it? I'd love to hear from you in the comments!
Check out my website here: https://www.julianmichaeltechnologies...
Follow my other socials here:
Instagram: / jmichaeltech
TikTok: / jmichaeltechnologies
Facebook: https://www.facebook.com/jmichaeltech...
Twitter: / jmichaeltech
#shorts
コメント