Skip to content

Instantly share code, notes, and snippets.

@jonathanduty
Created August 16, 2016 19:12
Show Gist options
  • Save jonathanduty/c3055e0c660bb4da36cee9f98377784f to your computer and use it in GitHub Desktop.
Save jonathanduty/c3055e0c660bb4da36cee9f98377784f to your computer and use it in GitHub Desktop.
Neato OnMain swift keyword.
import Foundation
func onMain(closure: () -> ()) {
if NSThread.isMainThread() {
closure()
}
else {
dispatch_async(dispatch_get_main_queue(), closure)
}
}
func delay(delay: NSTimeInterval, closure: () -> Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
@erolando
Copy link

erolando commented May 18, 2017

Swift 3:
func onMain(closure: @escaping () -> ()) {
if Thread.isMainThread {
closure()
}
else {
DispatchQueue.main.async(execute: closure)
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment