So I read that when running DispatchQueue.main.async { }
you don't need to declare [weak self]
. However, i joined a new project, and stumbled across this:
public func dispatchOnMain(execute: @escaping () -> Void) {
if Thread.isMainThread {
execute()
return
}
DispatchQueue.main.async(execute: execute)
}
Which is an open global function. From here on, doing something like:
class Foo {
func bar() {
dispatchOnMain {
// Do something
}
}
}
Will this dispatchOnMain {
require a weak self
? And why / why not?
You're way overthinking this. The need for weak self has nothing to do with what thread you're going to be on, and it has nothing to do with dispatch queues. If you're going to be worrying about weak self every time you see a pair of curly braces, you'll be a nervous wreck. 😃
Weak self has to do with whether there will be a retain cycle. Retain cycles are caused through long term storage of a closure by an object it captures.
Nothing like that is going on here. When you are just saying "perform this action now", regardless of the thread, no retain cycle arises. So no precautions are necessary.