Swift - delay code execution

Aus Wikizone
Wechseln zu: Navigation, Suche

Links

Swift - Snippets

how can i delay code execution for 0.2s in swift

There are a few ways to delay code execution in Swift:

   Use the sleep function from the sleep library:
import Foundation

// Delay code execution for 0.2 seconds
sleep(0.2)

This method is simple, but it is not recommended for use in production code because it blocks the main thread and can cause the user interface to become unresponsive.

   Use the DispatchQueue class from the Dispatch library:
import Dispatch

// Delay code execution for 0.2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
    // Code to be executed after the delay
}

This method uses the main dispatch queue to asynchronously schedule the code to be executed after the specified delay. This method does not block the main thread and is suitable for use in production code.

   Use the perform(inBackground:) method from the UIViewController class:
import UIKit

// Delay code execution for 0.2 seconds
perform(inBackground: {
    Thread.sleep(forTimeInterval: 0.2)
}) {
    // Code to be executed after the delay
}

This method is similar to the DispatchQueue method, but it is specific to view controllers and uses a background thread to execute the delayed code. This method does not block the main thread and is suitable for use in production code.

        sender.alpha = 0.5
        
        // Delay code execution for 0.2 seconds
        perform(afterDelay: 0.2) {
            // Code to be executed after the delay
            sender.alpha = 1.0
        }