Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

663
Vistas
How can I use async/await with SwiftUI in Swift 5.5?

I have been testing the async/await functionality previewed in the Swift 5.5 release, but I am unable to collect the results from an async function and display them using SwiftUI. Here is my code:

import SwiftUI

struct AsyncTestView: View {
    @State var text: String?

    // Async function
    func asyncGetText() async -> String {
        Thread.sleep(forTimeInterval: 10)
        return "My text"
    }
    
    // Stores the result of async function
    func fetchText() async {
        let text = await asyncGetText()
        DispatchQueue.main.async {
            self.text = text
        }
    }
    
    var body: some View {
        Text(text ?? "Loading")
            .onAppear(perform: fetchText)
    }
}

This results in the following error:

'async' call in a function that does not support concurrency
Add 'async' to function 'fetchText()' to make it asynchronous

Adding async to the fetchText() function then results in the following error on the .onAppear() function:

Invalid conversion from 'async' function of type '() async -> ()' to synchronous function type '() -> Void'

In this article, they use the @asyncHandler tag to annotate the fetchText function, however this results in the warning: '@asyncHandler' has been removed from the language'.

over 4 years ago · Santiago Trujillo
4 Respuestas
Responde la pregunta

0

I'm the author of the article you referenced.

As discussed in Discover concurrency in SwiftUI, views can make use of the new .task { } and .refreshable { } modifiers to fetch data asynchronously.

So you now have the following options to call your async code:

func someSyncMethod() {
  doSomeSyncWork()
  Task {
    await methodThatIsAsync()
  }
}
List {
}
.task {
  await methodThatIsAsync()
}
List {
}
.refreshable {
  await methodThatIsAsync()
}

If you're using a separate view model, make sure to mark it as @MainActor to ensure property updates get executed on the main actor.

I updated the code for my article: https://github.com/peterfriese/Swift-Async-Await-Experiments

over 4 years ago · Santiago Trujillo Denunciar

0

As per new informations in WWDC session Meet async/await in Swift WWDC, at 23m:28s this is now done using:

async {
   someState = await someAsyncFunction()
}

Screenshot from the session.

enter image description here

over 4 years ago · Santiago Trujillo Denunciar

0

I agree with @peter-friese's answer but will add for those reading this the change of syntax when bridging from sync to async:

The new syntax:

Task {
   someState = await someAsyncFunction()
}

Replaces this syntax:

async {
   someState = await someAsyncFunction()
}

... and the Task() initialiser can accept a priority parameter:

Task(priority: .userInitiated) {
   someState = await someAsyncFunction()
}
over 4 years ago · Santiago Trujillo Denunciar

0

import SwiftUI

struct AsyncTestView: View {
    @State var text = "Loading"

    // Async function
    func asyncGetText() async -> String {
        try? await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC)
        return "My text"
    }
    
    var body: some View {
        Text(text)
        .task {
             text = await asyncGetText()
        }
    }
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda