Con el código de muestra a continuación, realicé una prueba para comprender el mecanismo asíncrono y de espera en Swift. Se logra la secuencia de procesos. Mis impresiones de prueba en la consola aparecen en la secuencia prevista (paso 1-4). Sin embargo, lo que me desconcierta es que los mensajes de prueba, que aparecerán en la interfaz de usuario, no aparecen en la secuencia prevista. Ambos mensajes ( Message1 y Message2 ) aparecen juntos al final de todo el proceso después del paso 4. Entonces, ¿por qué Message1 no aparece justo después del paso 1 como está codificado?
import UIKit class ViewController: UIViewController { var testasyncDone = false @IBOutlet weak var MyButton2: UIButton! @IBOutlet weak var Message1: UITextField! @IBOutlet weak var Message2: UITextField! @IBAction func MyButton2pressed(_ sender: UIButton) { print("MyButton Pressed step 1") // This first message shall appear right after the button // is pressed Message1.text = "In Button action - start" // The async task is defined and started testasyncDone = false Task.detached { await self.testasync() print("MyButton Pressed step 4") } // The intention of the next lines is to hold the // processing of the main thread until the async task is // completed. var count = 0 repeat { count = count + 1 usleep(100000) print (count) } while testasyncDone == false && count < 100 // After the async task is done, the second message shall show up Message2.text = "In Button action - end" } func testasync() async { print("in testasync step 2") sleep(2) print("in testasync step 3") testasyncDone = true } }