Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Created September 26, 2016 05:55
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save sgr-ksmt/4880c5df5aeec9e558622cd6d5b477cb to your computer and use it in GitHub Desktop.
Save sgr-ksmt/4880c5df5aeec9e558622cd6d5b477cb to your computer and use it in GitHub Desktop.
Safe DispatchQueue.main.sync (Swift3.0)
extension DispatchQueue {
class func mainSyncSafe(execute work: () -> Void) {
if Thread.isMainThread {
work()
} else {
DispatchQueue.main.sync(execute: work)
}
}
class func mainSyncSafe<T>(execute work: () throws -> T) rethrows -> T {
if Thread.isMainThread {
return try work()
} else {
return try DispatchQueue.main.sync(execute: work)
}
}
}
@phlippieb
Copy link

Nice!

Did you know that you can do stuff like this?

let x = DispatchQueue.main.sync {
    return 10
}

I modified your gist to cater for that. Here's mine:

func syncSafe<T>(_ work: () -> T) -> T {
    if Thread.isMainThread {
        return work()
    } else {
        return DispatchQueue.main.sync {
            return work()
        }
    }
}

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