0
0
iOS Swiftmobile~5 mins

Await keyword in iOS Swift

Choose your learning style9 modes available
Introduction

The await keyword helps your app wait for a task to finish without freezing the screen. It makes your app smooth and responsive.

When loading data from the internet and you want to wait for the download to finish.
When reading a file from storage and you need the content before continuing.
When calling a slow function but want the app to stay responsive.
When you want to pause a function until another task completes.
Syntax
iOS Swift
let result = await someAsyncFunction()

You must use await inside an async function.

The function you call with await must be marked as async.

Examples
This function waits for downloadData() to finish before printing.
iOS Swift
func fetchData() async {
  let data = await downloadData()
  print(data)
}
This function returns a greeting string after waiting for getGreeting().
iOS Swift
func greet() async -> String {
  return await getGreeting()
}
Sample App

This SwiftUI view shows "Loading..." first. Then it waits 1 second using await inside fetchMessage(). After waiting, it updates the text to "Hello from async!" smoothly without freezing the app.

iOS Swift
import SwiftUI

struct ContentView: View {
  @State private var message = "Loading..."

  var body: some View {
    Text(message)
      .padding()
      .task {
        message = await fetchMessage()
      }
  }

  func fetchMessage() async -> String {
    try? await Task.sleep(nanoseconds: 1_000_000_000) // wait 1 second
    return "Hello from async!"
  }
}
OutputSuccess
Important Notes

Use await only inside async functions or closures.

Using await lets your app stay responsive while waiting.

Remember to mark functions that use await as async.

Summary

await pauses a function until an async task finishes.

It helps keep your app smooth and responsive.

Use await only inside async functions.