0
0
Swiftprogramming~3 mins

Why Async functions declaration in Swift? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could do many things at once without ever freezing or confusing you?

The Scenario

Imagine you want to fetch weather data from the internet and then show it in your app. If you do this step by step, waiting for each task to finish before starting the next, your app might freeze and feel slow.

The Problem

Doing tasks one after another without waiting properly can make your app unresponsive. You might write complicated code with many callbacks or timers, which is hard to read and easy to mess up.

The Solution

Async functions let you write code that waits for tasks to finish without freezing your app. They make your code cleaner and easier to understand by using simple keywords to mark functions that work asynchronously.

Before vs After
Before
func fetchData() {
  fetchFromNetwork { data in
    process(data)
  }
}
After
func fetchData() async {
  let data = await fetchFromNetwork()
  process(data)
}
What It Enables

Async functions let your app stay smooth and responsive while doing many tasks that take time, like loading data or waiting for user input.

Real Life Example

When you open a photo app, async functions help load pictures from the internet in the background so you can scroll smoothly without waiting.

Key Takeaways

Manual waiting can freeze apps and create messy code.

Async functions make waiting easy and keep apps responsive.

They simplify handling tasks that take time, improving user experience.