Avatar ·

How to make a delay in Swift: complete guide

Hello everyone! I'm a beginner in Swift and iOS development. I'm writing a simple training app — a countdown timer. I need that after pressing the "Start" button, the program waits 3 seconds and then performs some action (for example, shows a message or starts an animation).\n\nI tried using `sleep(3)`, but it seems to block the entire interface — the app freezes for 3 seconds, and buttons become unresponsive. That's not what I need.\n\nPlease tell me how to properly make a delay in Swift so that the interface remains responsive? Preferably with a code example for iOS (UIKit or SwiftUI). I've heard about `DispatchQueue.main.asyncAfter`, but I don't fully understand how it works.\n\nHere's my current (incorrect) code:\n\n```swift\n@IBAction func startButtonTapped(_ sender: UIButton)