Swift 5.5 introdujo async/await, transformando la forma de escribir código asíncrono. En lugar de callbacks anidados, el código asíncrono tiene la misma estructura lineal que el síncrono: el compilador transforma las suspensiones en máquinas de estado eficientes sin bloquear ningún hilo.
async func y await
import Foundation
func obtenerUsuario(id: Int) async throws -> String {
let url = URL(string: "https://api.ejemplo.com/users/(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return String(data: data, encoding: .utf8) ?? ""
}
// Llamar desde contexto async
Task {
do {
let nombre = try await obtenerUsuario(id: 1)
print("Usuario: (nombre)")
} catch {
print("Error: (error)")
}
}
await suspende sin bloquear el hilo
La palabra clave await marca los puntos de suspensión. El hilo queda libre para ejecutar otro trabajo mientras espera; cuando la operación termina, Swift reanuda la función en el contexto adecuado:
func procesarImagen(_ url: URL) async -> UIImage? {
// Suspende el contexto actual, no el hilo
guard let (data, _) = try? await URLSession.shared.data(from: url),
let imagen = UIImage(data: data) else { return nil }
return imagen
}
Convertir callbacks con withCheckedContinuation
func obtenerDatosLegacy() async -> Data {
await withCheckedContinuation { continuation in
apiAntigua.fetch { datos in
continuation.resume(returning: datos)
}
}
}
Task: lanzar trabajo asíncrono
// Task unstructured: lanza trabajo en background
let tarea = Task {
try await obtenerUsuario(id: 42)
}
// Obtener resultado
do {
let resultado = try await tarea.value
print(resultado)
} catch { print(error) }
// Cancelar
tarea.cancel()







