Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

63
Views
Need help to understand the order of execution in conjunction with async and await

With the sample code below I have made a test to understand the async and await mechanism in Swift. The sequence of processes is achieved. My test prints to the console do appear in the intended sequence (step 1-4). However, what puzzles me is that the test messages, which shall appear on the UI, do not show up in the intended sequence. Both messages (Message1 and Message2) appear together at the end of the entire process after step 4. So why does Message1 not appear right after step 1 as coded?

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
    }
}
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!