How to use dispatch_after in Swift 3, 4 and 5 for delayed execution?
Hello! I'm new to Swift and trying to migrate old code from Objective-C where I used dispatch_after for delayed execution. Previously I wrote something like:
```objective-c
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"2 seconds passed");
});
```
But in Swift 3 and above this doesn't work. I tried writing it like this:
```swift
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), DispatchQueue.main, {
print("2 seconds passed")
})
```
But Xcode gives an error: "Use of unresolved identifier 'dispatch_after'". I understand that GCD has changed significantly, but I can't find a clear example for Swift 3/4/5. Please explain how to properly make a 2-second delay with execution on the main thread.
No answers yet.
Log in to leave an answer
Blogs
Java for Machine Learning: Capabilities and Limitations