Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

phlippieb commented Mar 26, 2018

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