code delay in swift code example

Example 1: settimeout in swift

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds.
   // Code you want to be delayed
}

Example 2: swift thread.sleep

while (true){
    print("sleep for 2 seconds.")
    sleep(2) // working
}

Example 3: delay code execution swift 5

let timer = 1

DispatchQueue.main.asyncAfter(deadline: .now() + timer) {
    // code to execute after 1 second
}

Example 4: swift wait 5 seconds

sleep(5). // Argument is number of seconds