0

I have an old iOS application developed with Swift 1.2. In that used dispatch queues for speed up runtime.

dispatch_async(dispatch_get_main_queue()) { 

}

In Swift 4 I have tried by changing like below

DispatchQueue.main.async { [weak self] in
        if let strongSelf = self {
            strongSelf.imapFetchFoldersOp?.start({ (error, folders) -> Void in
                    if let error = error {
                        #if DEBUG
                            print("\(String(describing: error._userInfo))")
                        #endif
                    } else {
                        strongSelf.folders = folders! as NSArray
                        strongSelf.fetchInfoForBoxes()
                        print("Floders :\(folders!)")
                    }
                })
            }
        }

Did I do it correctly or do I need to modify?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253

2 Answers2

1

Don't you need to just dispatch to a background queue? Or does it need to run on the main thread?

    DispatchQueue.global().async {…}
Larvell Jones
  • 159
  • 2
  • 15
0

If you are already on the main thread, I don't see the reason to dispatch it to it asynchronously, I believe in your case it's even better to do:

self.imapFetchFoldersOp?.start({ (error, folders) -> Void in
    if let error = error {
        #if DEBUG
             print("\(String(describing: error._userInfo))")
        #endif
    } else {
        self.folders = folders! as NSArray
        self.fetchInfoForBoxes()
        print("Folders :\(folders!)")
    }
})

Explanation: you are already on the main thread, dispatching the task on the main thread asynchronously will just enqueue that task to the main thread, so that it will get executed not right now, but when the current tasks will end (e.g., drawing, etc.). I'm assuming that imapFetchFoldersOp is a task that downloads some data from a mail server - in that case, if you are using URLSession or some library, most probably it will be executed on some background thread, thus that should not imply any overhead.

Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90